disable ImageBackgroundFilter.BackgroundFilterRotated_GL cc_unittests on Dr.Memory...
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blobf89e94655426bfac2351c15c0a4b1f7d579de9e2
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_attachment_set.h"
23 #include "ipc/ipc_message_utils.h"
25 namespace IPC {
27 ChannelWin::State::State(ChannelWin* channel) : is_pending(false) {
28 memset(&context.overlapped, 0, sizeof(context.overlapped));
29 context.handler = channel;
32 ChannelWin::State::~State() {
33 static_assert(offsetof(ChannelWin::State, context) == 0,
34 "ChannelWin::State should have context as its first data"
35 "member.");
38 ChannelWin::ChannelWin(const IPC::ChannelHandle& channel_handle,
39 Mode mode,
40 Listener* listener,
41 AttachmentBroker* broker)
42 : ChannelReader(listener),
43 input_state_(this),
44 output_state_(this),
45 peer_pid_(base::kNullProcessId),
46 waiting_connect_(mode & MODE_SERVER_FLAG),
47 processing_incoming_(false),
48 validate_client_(false),
49 client_secret_(0),
50 broker_(broker),
51 weak_factory_(this) {
52 CreatePipe(channel_handle, mode);
55 ChannelWin::~ChannelWin() {
56 CleanUp();
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 OutputElement* element = output_queue_.front();
79 output_queue_.pop();
80 delete element;
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 OutputElement* element = new OutputElement(message);
131 output_queue_.push(element);
133 #if USE_ATTACHMENT_BROKER
134 if (message->HasBrokerableAttachments()) {
135 // |output_queue_| takes ownership of |ids.buffer|.
136 Message::SerializedAttachmentIds ids =
137 message->SerializedIdsOfBrokerableAttachments();
138 OutputElement* new_element = new OutputElement(ids.buffer, ids.size);
139 output_queue_.push(new_element);
141 #endif
143 // ensure waiting to write
144 if (!waiting_connect_) {
145 if (!output_state_.is_pending) {
146 if (!ProcessOutgoingMessages(NULL, 0))
147 return false;
151 return true;
154 void ChannelWin::FlushPrelimQueue() {
155 DCHECK_NE(peer_pid_, base::kNullProcessId);
157 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
158 // is critical that |prelim_queue_| appears empty.
159 std::queue<Message*> prelim_queue;
160 prelim_queue_.swap(prelim_queue);
162 while (!prelim_queue.empty()) {
163 Message* m = prelim_queue.front();
164 ProcessMessageForDelivery(m);
165 prelim_queue.pop();
169 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
170 return broker_;
173 base::ProcessId ChannelWin::GetPeerPID() const {
174 return peer_pid_;
177 base::ProcessId ChannelWin::GetSelfPID() const {
178 return GetCurrentProcessId();
181 // static
182 bool ChannelWin::IsNamedServerInitialized(
183 const std::string& channel_id) {
184 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
185 return true;
186 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
187 // connection.
188 return GetLastError() == ERROR_SEM_TIMEOUT;
191 ChannelWin::ReadState ChannelWin::ReadData(
192 char* buffer,
193 int buffer_len,
194 int* /* bytes_read */) {
195 if (!pipe_.IsValid())
196 return READ_FAILED;
198 DWORD bytes_read = 0;
199 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
200 &bytes_read, &input_state_.context.overlapped);
201 if (!ok) {
202 DWORD err = GetLastError();
203 if (err == ERROR_IO_PENDING) {
204 input_state_.is_pending = true;
205 return READ_PENDING;
207 LOG(ERROR) << "pipe error: " << err;
208 return READ_FAILED;
211 // We could return READ_SUCCEEDED here. But the way that this code is
212 // structured we instead go back to the message loop. Our completion port
213 // will be signalled even in the "synchronously completed" state.
215 // This allows us to potentially process some outgoing messages and
216 // interleave other work on this thread when we're getting hammered with
217 // input messages. Potentially, this could be tuned to be more efficient
218 // with some testing.
219 input_state_.is_pending = true;
220 return READ_PENDING;
223 bool ChannelWin::ShouldDispatchInputMessage(Message* msg) {
224 // Make sure we get a hello when client validation is required.
225 if (validate_client_)
226 return IsHelloMessage(*msg);
227 return true;
230 bool ChannelWin::GetNonBrokeredAttachments(Message* msg) {
231 return true;
234 void ChannelWin::HandleInternalMessage(const Message& msg) {
235 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
236 // The hello message contains one parameter containing the PID.
237 base::PickleIterator it(msg);
238 int32 claimed_pid;
239 bool failed = !it.ReadInt(&claimed_pid);
241 if (!failed && validate_client_) {
242 int32 secret;
243 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
246 if (failed) {
247 NOTREACHED();
248 Close();
249 listener()->OnChannelError();
250 return;
253 peer_pid_ = claimed_pid;
254 // Validation completed.
255 validate_client_ = false;
257 FlushPrelimQueue();
259 listener()->OnChannelConnected(claimed_pid);
262 base::ProcessId ChannelWin::GetSenderPID() {
263 return GetPeerPID();
266 bool ChannelWin::IsAttachmentBrokerEndpoint() {
267 return is_attachment_broker_endpoint();
270 bool ChannelWin::DidEmptyInputBuffers() {
271 // We don't need to do anything here.
272 return true;
275 // static
276 const base::string16 ChannelWin::PipeName(
277 const std::string& channel_id, int32* secret) {
278 std::string name("\\\\.\\pipe\\chrome.");
280 // Prevent the shared secret from ending up in the pipe name.
281 size_t index = channel_id.find_first_of('\\');
282 if (index != std::string::npos) {
283 if (secret) // Retrieve the secret if asked for.
284 base::StringToInt(channel_id.substr(index + 1), secret);
285 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
288 // This case is here to support predictable named pipes in tests.
289 if (secret)
290 *secret = 0;
291 return base::ASCIIToUTF16(name.append(channel_id));
294 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
295 Mode mode) {
296 DCHECK(!pipe_.IsValid());
297 base::string16 pipe_name;
298 // If we already have a valid pipe for channel just copy it.
299 if (channel_handle.pipe.handle) {
300 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
301 // favor of two independent entities (name/file), or it should be a move-
302 // only type with a base::File member. In any case, this code should not
303 // call DuplicateHandle.
304 DCHECK(channel_handle.name.empty());
305 pipe_name = L"Not Available"; // Just used for LOG
306 // Check that the given pipe confirms to the specified mode. We can
307 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
308 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
309 DWORD flags = 0;
310 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
311 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
312 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
313 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
314 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
315 return false;
317 HANDLE local_handle;
318 if (!DuplicateHandle(GetCurrentProcess(),
319 channel_handle.pipe.handle,
320 GetCurrentProcess(),
321 &local_handle,
323 FALSE,
324 DUPLICATE_SAME_ACCESS)) {
325 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
326 return false;
328 pipe_.Set(local_handle);
329 } else if (mode & MODE_SERVER_FLAG) {
330 DCHECK(!channel_handle.pipe.handle);
331 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
332 FILE_FLAG_FIRST_PIPE_INSTANCE;
333 pipe_name = PipeName(channel_handle.name, &client_secret_);
334 validate_client_ = !!client_secret_;
335 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
336 open_mode,
337 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
339 Channel::kReadBufferSize,
340 Channel::kReadBufferSize,
341 5000,
342 NULL));
343 } else if (mode & MODE_CLIENT_FLAG) {
344 DCHECK(!channel_handle.pipe.handle);
345 pipe_name = PipeName(channel_handle.name, &client_secret_);
346 pipe_.Set(CreateFileW(pipe_name.c_str(),
347 GENERIC_READ | GENERIC_WRITE,
349 NULL,
350 OPEN_EXISTING,
351 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
352 FILE_FLAG_OVERLAPPED,
353 NULL));
354 } else {
355 NOTREACHED();
358 if (!pipe_.IsValid()) {
359 // If this process is being closed, the pipe may be gone already.
360 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
361 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
362 return false;
365 // Create the Hello message to be sent when Connect is called
366 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
367 HELLO_MESSAGE_TYPE,
368 IPC::Message::PRIORITY_NORMAL));
370 // Don't send the secret to the untrusted process, and don't send a secret
371 // if the value is zero (for IPC backwards compatability).
372 int32 secret = validate_client_ ? 0 : client_secret_;
373 if (!m->WriteInt(GetCurrentProcessId()) ||
374 (secret && !m->WriteUInt32(secret))) {
375 pipe_.Close();
376 return false;
379 OutputElement* element = new OutputElement(m.release());
380 output_queue_.push(element);
381 return true;
384 bool ChannelWin::Connect() {
385 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
387 if (!thread_check_.get())
388 thread_check_.reset(new base::ThreadChecker());
390 if (!pipe_.IsValid())
391 return false;
393 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
395 // Check to see if there is a client connected to our pipe...
396 if (waiting_connect_)
397 ProcessConnection();
399 if (!input_state_.is_pending) {
400 // Complete setup asynchronously. By not setting input_state_.is_pending
401 // to true, we indicate to OnIOCompleted that this is the special
402 // initialization signal.
403 base::MessageLoopForIO::current()->PostTask(
404 FROM_HERE,
405 base::Bind(&ChannelWin::OnIOCompleted,
406 weak_factory_.GetWeakPtr(),
407 &input_state_.context,
409 0));
412 if (!waiting_connect_)
413 ProcessOutgoingMessages(NULL, 0);
414 return true;
417 bool ChannelWin::ProcessConnection() {
418 DCHECK(thread_check_->CalledOnValidThread());
419 if (input_state_.is_pending)
420 input_state_.is_pending = false;
422 // Do we have a client connected to our pipe?
423 if (!pipe_.IsValid())
424 return false;
426 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
427 DWORD err = GetLastError();
428 if (ok) {
429 // Uhm, the API documentation says that this function should never
430 // return success when used in overlapped mode.
431 NOTREACHED();
432 return false;
435 switch (err) {
436 case ERROR_IO_PENDING:
437 input_state_.is_pending = true;
438 break;
439 case ERROR_PIPE_CONNECTED:
440 waiting_connect_ = false;
441 break;
442 case ERROR_NO_DATA:
443 // The pipe is being closed.
444 return false;
445 default:
446 NOTREACHED();
447 return false;
450 return true;
453 bool ChannelWin::ProcessOutgoingMessages(
454 base::MessageLoopForIO::IOContext* context,
455 DWORD bytes_written) {
456 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
457 // no connection?
458 DCHECK(thread_check_->CalledOnValidThread());
460 if (output_state_.is_pending) {
461 DCHECK(context);
462 output_state_.is_pending = false;
463 if (!context || bytes_written == 0) {
464 DWORD err = GetLastError();
465 LOG(ERROR) << "pipe error: " << err;
466 return false;
468 // Message was sent.
469 CHECK(!output_queue_.empty());
470 OutputElement* element = output_queue_.front();
471 output_queue_.pop();
472 delete element;
475 if (output_queue_.empty())
476 return true;
478 if (!pipe_.IsValid())
479 return false;
481 // Write to pipe...
482 OutputElement* element = output_queue_.front();
483 DCHECK(element->size() <= INT_MAX);
484 BOOL ok = WriteFile(pipe_.Get(), element->data(),
485 static_cast<uint32>(element->size()), NULL,
486 &output_state_.context.overlapped);
487 if (!ok) {
488 DWORD write_error = GetLastError();
489 if (write_error == ERROR_IO_PENDING) {
490 output_state_.is_pending = true;
492 const Message* m = element->get_message();
493 if (m) {
494 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
495 << " with type " << m->type();
498 return true;
500 LOG(ERROR) << "pipe error: " << write_error;
501 return false;
504 const Message* m = element->get_message();
505 if (m) {
506 DVLOG(2) << "sent message @" << m << " on channel @" << this
507 << " with type " << m->type();
510 output_state_.is_pending = true;
511 return true;
514 void ChannelWin::OnIOCompleted(
515 base::MessageLoopForIO::IOContext* context,
516 DWORD bytes_transfered,
517 DWORD error) {
518 bool ok = true;
519 DCHECK(thread_check_->CalledOnValidThread());
520 if (context == &input_state_.context) {
521 if (waiting_connect_) {
522 if (!ProcessConnection())
523 return;
524 // We may have some messages queued up to send...
525 if (!output_queue_.empty() && !output_state_.is_pending)
526 ProcessOutgoingMessages(NULL, 0);
527 if (input_state_.is_pending)
528 return;
529 // else, fall-through and look for incoming messages...
532 // We don't support recursion through OnMessageReceived yet!
533 DCHECK(!processing_incoming_);
534 base::AutoReset<bool> auto_reset_processing_incoming(
535 &processing_incoming_, true);
537 // Process the new data.
538 if (input_state_.is_pending) {
539 // This is the normal case for everything except the initialization step.
540 input_state_.is_pending = false;
541 if (!bytes_transfered) {
542 ok = false;
543 } else if (pipe_.IsValid()) {
544 ok = (AsyncReadComplete(bytes_transfered) != DISPATCH_ERROR);
546 } else {
547 DCHECK(!bytes_transfered);
550 // Request more data.
551 if (ok)
552 ok = (ProcessIncomingMessages() != DISPATCH_ERROR);
553 } else {
554 DCHECK(context == &output_state_.context);
555 CHECK(output_state_.is_pending);
556 ok = ProcessOutgoingMessages(context, bytes_transfered);
558 if (!ok && pipe_.IsValid()) {
559 // We don't want to re-enter Close().
560 Close();
561 listener()->OnChannelError();
565 //------------------------------------------------------------------------------
566 // Channel's methods
568 // static
569 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
570 Mode mode,
571 Listener* listener,
572 AttachmentBroker* broker) {
573 return scoped_ptr<Channel>(
574 new ChannelWin(channel_handle, mode, listener, broker));
577 // static
578 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
579 return ChannelWin::IsNamedServerInitialized(channel_id);
582 // static
583 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
584 // Windows pipes can be enumerated by low-privileged processes. So, we
585 // append a strong random value after the \ character. This value is not
586 // included in the pipe name, but sent as part of the client hello, to
587 // hijacking the pipe name to spoof the client.
589 std::string id = prefix;
590 if (!id.empty())
591 id.append(".");
593 int secret;
594 do { // Guarantee we get a non-zero value.
595 secret = base::RandInt(0, std::numeric_limits<int>::max());
596 } while (secret == 0);
598 id.append(GenerateUniqueRandomChannelID());
599 return id.append(base::StringPrintf("\\%d", secret));
602 } // namespace IPC