cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob84281509d7668db5139570c535e9d446bcf3d774
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 <stdint.h>
8 #include <windows.h>
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/compiler_specific.h"
13 #include "base/logging.h"
14 #include "base/pickle.h"
15 #include "base/process/process_handle.h"
16 #include "base/rand_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/threading/thread_checker.h"
20 #include "base/win/scoped_handle.h"
21 #include "ipc/ipc_listener.h"
22 #include "ipc/ipc_logging.h"
23 #include "ipc/ipc_message_attachment_set.h"
24 #include "ipc/ipc_message_utils.h"
26 namespace IPC {
28 ChannelWin::State::State(ChannelWin* channel) : is_pending(false) {
29 memset(&context.overlapped, 0, sizeof(context.overlapped));
30 context.handler = channel;
33 ChannelWin::State::~State() {
34 static_assert(offsetof(ChannelWin::State, context) == 0,
35 "ChannelWin::State should have context as its first data"
36 "member.");
39 ChannelWin::ChannelWin(const IPC::ChannelHandle& channel_handle,
40 Mode mode,
41 Listener* listener,
42 AttachmentBroker* broker)
43 : ChannelReader(listener),
44 input_state_(this),
45 output_state_(this),
46 peer_pid_(base::kNullProcessId),
47 waiting_connect_(mode & MODE_SERVER_FLAG),
48 processing_incoming_(false),
49 validate_client_(false),
50 client_secret_(0),
51 broker_(broker),
52 weak_factory_(this) {
53 CreatePipe(channel_handle, mode);
56 ChannelWin::~ChannelWin() {
57 Close();
60 void ChannelWin::Close() {
61 if (thread_check_.get())
62 DCHECK(thread_check_->CalledOnValidThread());
64 if (input_state_.is_pending || output_state_.is_pending)
65 CancelIo(pipe_.Get());
67 // Closing the handle at this point prevents us from issuing more requests
68 // form OnIOCompleted().
69 if (pipe_.IsValid())
70 pipe_.Close();
72 // Make sure all IO has completed.
73 while (input_state_.is_pending || output_state_.is_pending) {
74 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
77 while (!output_queue_.empty()) {
78 Message* m = output_queue_.front();
79 output_queue_.pop();
80 delete m;
84 bool ChannelWin::Send(Message* message) {
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 if (!prelim_queue_.empty()) {
91 prelim_queue_.push(message);
92 return true;
95 if (message->HasBrokerableAttachments() &&
96 peer_pid_ == base::kNullProcessId) {
97 prelim_queue_.push(message);
98 return true;
101 return ProcessMessageForDelivery(message);
104 bool ChannelWin::ProcessMessageForDelivery(Message* message) {
105 // Sending a brokerable attachment requires a call to Channel::Send(), so
106 // both Send() and ProcessMessageForDelivery() may be re-entrant. Brokered
107 // attachments must be sent before the Message itself.
108 if (message->HasBrokerableAttachments()) {
109 DCHECK(broker_);
110 DCHECK(peer_pid_ != base::kNullProcessId);
111 for (const BrokerableAttachment* attachment :
112 message->attachment_set()->PeekBrokerableAttachments()) {
113 if (!broker_->SendAttachmentToProcess(attachment, peer_pid_)) {
114 delete message;
115 return false;
120 #ifdef IPC_MESSAGE_LOG_ENABLED
121 Logging::GetInstance()->OnSendMessage(message, "");
122 #endif
124 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
125 "ChannelWin::ProcessMessageForDelivery",
126 message->flags(),
127 TRACE_EVENT_FLAG_FLOW_OUT);
129 // |output_queue_| takes ownership of |message|.
130 output_queue_.push(message);
131 // ensure waiting to write
132 if (!waiting_connect_) {
133 if (!output_state_.is_pending) {
134 if (!ProcessOutgoingMessages(NULL, 0))
135 return false;
139 return true;
142 void ChannelWin::FlushPrelimQueue() {
143 DCHECK_NE(peer_pid_, base::kNullProcessId);
145 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
146 // is critical that |prelim_queue_| appears empty.
147 std::queue<Message*> prelim_queue;
148 prelim_queue_.swap(prelim_queue);
150 while (!prelim_queue.empty()) {
151 Message* m = prelim_queue.front();
152 ProcessMessageForDelivery(m);
153 prelim_queue.pop();
157 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
158 return broker_;
161 base::ProcessId ChannelWin::GetPeerPID() const {
162 return peer_pid_;
165 base::ProcessId ChannelWin::GetSelfPID() const {
166 return GetCurrentProcessId();
169 // static
170 bool ChannelWin::IsNamedServerInitialized(
171 const std::string& channel_id) {
172 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
173 return true;
174 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
175 // connection.
176 return GetLastError() == ERROR_SEM_TIMEOUT;
179 ChannelWin::ReadState ChannelWin::ReadData(
180 char* buffer,
181 int buffer_len,
182 int* /* bytes_read */) {
183 if (!pipe_.IsValid())
184 return READ_FAILED;
186 DWORD bytes_read = 0;
187 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
188 &bytes_read, &input_state_.context.overlapped);
189 if (!ok) {
190 DWORD err = GetLastError();
191 if (err == ERROR_IO_PENDING) {
192 input_state_.is_pending = true;
193 return READ_PENDING;
195 LOG(ERROR) << "pipe error: " << err;
196 return READ_FAILED;
199 // We could return READ_SUCCEEDED here. But the way that this code is
200 // structured we instead go back to the message loop. Our completion port
201 // will be signalled even in the "synchronously completed" state.
203 // This allows us to potentially process some outgoing messages and
204 // interleave other work on this thread when we're getting hammered with
205 // input messages. Potentially, this could be tuned to be more efficient
206 // with some testing.
207 input_state_.is_pending = true;
208 return READ_PENDING;
211 bool ChannelWin::ShouldDispatchInputMessage(Message* msg) {
212 // Make sure we get a hello when client validation is required.
213 if (validate_client_)
214 return IsHelloMessage(*msg);
215 return true;
218 bool ChannelWin::GetNonBrokeredAttachments(Message* msg) {
219 return true;
222 void ChannelWin::HandleInternalMessage(const Message& msg) {
223 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
224 // The hello message contains one parameter containing the PID.
225 base::PickleIterator it(msg);
226 int32_t claimed_pid;
227 bool failed = !it.ReadInt(&claimed_pid);
229 if (!failed && validate_client_) {
230 int32_t secret;
231 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
234 if (failed) {
235 NOTREACHED();
236 Close();
237 listener()->OnChannelError();
238 return;
241 peer_pid_ = claimed_pid;
242 // Validation completed.
243 validate_client_ = false;
245 FlushPrelimQueue();
247 listener()->OnChannelConnected(claimed_pid);
250 base::ProcessId ChannelWin::GetSenderPID() {
251 return GetPeerPID();
254 bool ChannelWin::IsAttachmentBrokerEndpoint() {
255 return is_attachment_broker_endpoint();
258 bool ChannelWin::DidEmptyInputBuffers() {
259 // We don't need to do anything here.
260 return true;
263 // static
264 const base::string16 ChannelWin::PipeName(const std::string& channel_id,
265 int32_t* secret) {
266 std::string name("\\\\.\\pipe\\chrome.");
268 // Prevent the shared secret from ending up in the pipe name.
269 size_t index = channel_id.find_first_of('\\');
270 if (index != std::string::npos) {
271 if (secret) // Retrieve the secret if asked for.
272 base::StringToInt(channel_id.substr(index + 1), secret);
273 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
276 // This case is here to support predictable named pipes in tests.
277 if (secret)
278 *secret = 0;
279 return base::ASCIIToUTF16(name.append(channel_id));
282 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
283 Mode mode) {
284 DCHECK(!pipe_.IsValid());
285 base::string16 pipe_name;
286 // If we already have a valid pipe for channel just copy it.
287 if (channel_handle.pipe.handle) {
288 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
289 // favor of two independent entities (name/file), or it should be a move-
290 // only type with a base::File member. In any case, this code should not
291 // call DuplicateHandle.
292 DCHECK(channel_handle.name.empty());
293 pipe_name = L"Not Available"; // Just used for LOG
294 // Check that the given pipe confirms to the specified mode. We can
295 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
296 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
297 DWORD flags = 0;
298 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
299 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
300 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
301 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
302 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
303 return false;
305 HANDLE local_handle;
306 if (!DuplicateHandle(GetCurrentProcess(),
307 channel_handle.pipe.handle,
308 GetCurrentProcess(),
309 &local_handle,
311 FALSE,
312 DUPLICATE_SAME_ACCESS)) {
313 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
314 return false;
316 pipe_.Set(local_handle);
317 } else if (mode & MODE_SERVER_FLAG) {
318 DCHECK(!channel_handle.pipe.handle);
319 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
320 FILE_FLAG_FIRST_PIPE_INSTANCE;
321 pipe_name = PipeName(channel_handle.name, &client_secret_);
322 validate_client_ = !!client_secret_;
323 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
324 open_mode,
325 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
327 Channel::kReadBufferSize,
328 Channel::kReadBufferSize,
329 5000,
330 NULL));
331 } else if (mode & MODE_CLIENT_FLAG) {
332 DCHECK(!channel_handle.pipe.handle);
333 pipe_name = PipeName(channel_handle.name, &client_secret_);
334 pipe_.Set(CreateFileW(pipe_name.c_str(),
335 GENERIC_READ | GENERIC_WRITE,
337 NULL,
338 OPEN_EXISTING,
339 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
340 FILE_FLAG_OVERLAPPED,
341 NULL));
342 } else {
343 NOTREACHED();
346 if (!pipe_.IsValid()) {
347 // If this process is being closed, the pipe may be gone already.
348 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
349 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
350 return false;
353 // Create the Hello message to be sent when Connect is called
354 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
355 HELLO_MESSAGE_TYPE,
356 IPC::Message::PRIORITY_NORMAL));
358 // Don't send the secret to the untrusted process, and don't send a secret
359 // if the value is zero (for IPC backwards compatability).
360 int32_t secret = validate_client_ ? 0 : client_secret_;
361 if (!m->WriteInt(GetCurrentProcessId()) ||
362 (secret && !m->WriteUInt32(secret))) {
363 pipe_.Close();
364 return false;
367 output_queue_.push(m.release());
368 return true;
371 bool ChannelWin::Connect() {
372 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
374 if (!thread_check_.get())
375 thread_check_.reset(new base::ThreadChecker());
377 if (!pipe_.IsValid())
378 return false;
380 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
382 // Check to see if there is a client connected to our pipe...
383 if (waiting_connect_)
384 ProcessConnection();
386 if (!input_state_.is_pending) {
387 // Complete setup asynchronously. By not setting input_state_.is_pending
388 // to true, we indicate to OnIOCompleted that this is the special
389 // initialization signal.
390 base::MessageLoopForIO::current()->PostTask(
391 FROM_HERE,
392 base::Bind(&ChannelWin::OnIOCompleted,
393 weak_factory_.GetWeakPtr(),
394 &input_state_.context,
396 0));
399 if (!waiting_connect_)
400 ProcessOutgoingMessages(NULL, 0);
401 return true;
404 bool ChannelWin::ProcessConnection() {
405 DCHECK(thread_check_->CalledOnValidThread());
406 if (input_state_.is_pending)
407 input_state_.is_pending = false;
409 // Do we have a client connected to our pipe?
410 if (!pipe_.IsValid())
411 return false;
413 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
414 DWORD err = GetLastError();
415 if (ok) {
416 // Uhm, the API documentation says that this function should never
417 // return success when used in overlapped mode.
418 NOTREACHED();
419 return false;
422 switch (err) {
423 case ERROR_IO_PENDING:
424 input_state_.is_pending = true;
425 break;
426 case ERROR_PIPE_CONNECTED:
427 waiting_connect_ = false;
428 break;
429 case ERROR_NO_DATA:
430 // The pipe is being closed.
431 return false;
432 default:
433 NOTREACHED();
434 return false;
437 return true;
440 bool ChannelWin::ProcessOutgoingMessages(
441 base::MessageLoopForIO::IOContext* context,
442 DWORD bytes_written) {
443 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
444 // no connection?
445 DCHECK(thread_check_->CalledOnValidThread());
447 if (output_state_.is_pending) {
448 DCHECK(context);
449 output_state_.is_pending = false;
450 if (!context || bytes_written == 0) {
451 DWORD err = GetLastError();
452 LOG(ERROR) << "pipe error: " << err;
453 return false;
455 // Message was sent.
456 CHECK(!output_queue_.empty());
457 Message* m = output_queue_.front();
458 output_queue_.pop();
459 delete m;
462 if (output_queue_.empty())
463 return true;
465 if (!pipe_.IsValid())
466 return false;
468 // Write to pipe...
469 Message* m = output_queue_.front();
470 DCHECK(m->size() <= INT_MAX);
471 BOOL ok = WriteFile(pipe_.Get(),
472 m->data(),
473 static_cast<uint32_t>(m->size()),
474 NULL,
475 &output_state_.context.overlapped);
476 if (!ok) {
477 DWORD write_error = GetLastError();
478 if (write_error == ERROR_IO_PENDING) {
479 output_state_.is_pending = true;
481 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
482 << " with type " << m->type();
484 return true;
486 LOG(ERROR) << "pipe error: " << write_error;
487 return false;
490 DVLOG(2) << "sent message @" << m << " on channel @" << this
491 << " with type " << m->type();
493 output_state_.is_pending = true;
494 return true;
497 void ChannelWin::OnIOCompleted(
498 base::MessageLoopForIO::IOContext* context,
499 DWORD bytes_transfered,
500 DWORD error) {
501 bool ok = true;
502 DCHECK(thread_check_->CalledOnValidThread());
503 if (context == &input_state_.context) {
504 if (waiting_connect_) {
505 if (!ProcessConnection())
506 return;
507 // We may have some messages queued up to send...
508 if (!output_queue_.empty() && !output_state_.is_pending)
509 ProcessOutgoingMessages(NULL, 0);
510 if (input_state_.is_pending)
511 return;
512 // else, fall-through and look for incoming messages...
515 // We don't support recursion through OnMessageReceived yet!
516 DCHECK(!processing_incoming_);
517 base::AutoReset<bool> auto_reset_processing_incoming(
518 &processing_incoming_, true);
520 // Process the new data.
521 if (input_state_.is_pending) {
522 // This is the normal case for everything except the initialization step.
523 input_state_.is_pending = false;
524 if (!bytes_transfered) {
525 ok = false;
526 } else if (pipe_.IsValid()) {
527 ok = (AsyncReadComplete(bytes_transfered) != DISPATCH_ERROR);
529 } else {
530 DCHECK(!bytes_transfered);
533 // Request more data.
534 if (ok)
535 ok = (ProcessIncomingMessages() != DISPATCH_ERROR);
536 } else {
537 DCHECK(context == &output_state_.context);
538 CHECK(output_state_.is_pending);
539 ok = ProcessOutgoingMessages(context, bytes_transfered);
541 if (!ok && pipe_.IsValid()) {
542 // We don't want to re-enter Close().
543 Close();
544 listener()->OnChannelError();
548 //------------------------------------------------------------------------------
549 // Channel's methods
551 // static
552 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
553 Mode mode,
554 Listener* listener,
555 AttachmentBroker* broker) {
556 return scoped_ptr<Channel>(
557 new ChannelWin(channel_handle, mode, listener, broker));
560 // static
561 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
562 return ChannelWin::IsNamedServerInitialized(channel_id);
565 // static
566 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
567 // Windows pipes can be enumerated by low-privileged processes. So, we
568 // append a strong random value after the \ character. This value is not
569 // included in the pipe name, but sent as part of the client hello, to
570 // hijacking the pipe name to spoof the client.
572 std::string id = prefix;
573 if (!id.empty())
574 id.append(".");
576 int secret;
577 do { // Guarantee we get a non-zero value.
578 secret = base::RandInt(0, std::numeric_limits<int>::max());
579 } while (secret == 0);
581 id.append(GenerateUniqueRandomChannelID());
582 return id.append(base::StringPrintf("\\%d", secret));
585 } // namespace IPC