Add scoped_ptr-safe base::Value to Dictionary/List conversion functions.
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob0fa5d4dedecb411feba6ae56a3ab67d1e3482ce4
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 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 // TODO(erikchen): Serialize the brokerable attachments and add them to the
134 // output_queue_. http://crbug.com/493414.
136 // ensure waiting to write
137 if (!waiting_connect_) {
138 if (!output_state_.is_pending) {
139 if (!ProcessOutgoingMessages(NULL, 0))
140 return false;
144 return true;
147 void ChannelWin::FlushPrelimQueue() {
148 DCHECK_NE(peer_pid_, base::kNullProcessId);
150 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
151 // is critical that |prelim_queue_| appears empty.
152 std::queue<Message*> prelim_queue;
153 prelim_queue_.swap(prelim_queue);
155 while (!prelim_queue.empty()) {
156 Message* m = prelim_queue.front();
157 ProcessMessageForDelivery(m);
158 prelim_queue.pop();
162 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
163 return broker_;
166 base::ProcessId ChannelWin::GetPeerPID() const {
167 return peer_pid_;
170 base::ProcessId ChannelWin::GetSelfPID() const {
171 return GetCurrentProcessId();
174 // static
175 bool ChannelWin::IsNamedServerInitialized(
176 const std::string& channel_id) {
177 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
178 return true;
179 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
180 // connection.
181 return GetLastError() == ERROR_SEM_TIMEOUT;
184 ChannelWin::ReadState ChannelWin::ReadData(
185 char* buffer,
186 int buffer_len,
187 int* /* bytes_read */) {
188 if (!pipe_.IsValid())
189 return READ_FAILED;
191 DWORD bytes_read = 0;
192 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
193 &bytes_read, &input_state_.context.overlapped);
194 if (!ok) {
195 DWORD err = GetLastError();
196 if (err == ERROR_IO_PENDING) {
197 input_state_.is_pending = true;
198 return READ_PENDING;
200 LOG(ERROR) << "pipe error: " << err;
201 return READ_FAILED;
204 // We could return READ_SUCCEEDED here. But the way that this code is
205 // structured we instead go back to the message loop. Our completion port
206 // will be signalled even in the "synchronously completed" state.
208 // This allows us to potentially process some outgoing messages and
209 // interleave other work on this thread when we're getting hammered with
210 // input messages. Potentially, this could be tuned to be more efficient
211 // with some testing.
212 input_state_.is_pending = true;
213 return READ_PENDING;
216 bool ChannelWin::ShouldDispatchInputMessage(Message* msg) {
217 // Make sure we get a hello when client validation is required.
218 if (validate_client_)
219 return IsHelloMessage(*msg);
220 return true;
223 bool ChannelWin::GetNonBrokeredAttachments(Message* msg) {
224 return true;
227 void ChannelWin::HandleInternalMessage(const Message& msg) {
228 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
229 // The hello message contains one parameter containing the PID.
230 base::PickleIterator it(msg);
231 int32_t claimed_pid;
232 bool failed = !it.ReadInt(&claimed_pid);
234 if (!failed && validate_client_) {
235 int32_t secret;
236 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
239 if (failed) {
240 NOTREACHED();
241 Close();
242 listener()->OnChannelError();
243 return;
246 peer_pid_ = claimed_pid;
247 // Validation completed.
248 validate_client_ = false;
250 FlushPrelimQueue();
252 listener()->OnChannelConnected(claimed_pid);
255 base::ProcessId ChannelWin::GetSenderPID() {
256 return GetPeerPID();
259 bool ChannelWin::IsAttachmentBrokerEndpoint() {
260 return is_attachment_broker_endpoint();
263 bool ChannelWin::DidEmptyInputBuffers() {
264 // We don't need to do anything here.
265 return true;
268 // static
269 const base::string16 ChannelWin::PipeName(const std::string& channel_id,
270 int32_t* secret) {
271 std::string name("\\\\.\\pipe\\chrome.");
273 // Prevent the shared secret from ending up in the pipe name.
274 size_t index = channel_id.find_first_of('\\');
275 if (index != std::string::npos) {
276 if (secret) // Retrieve the secret if asked for.
277 base::StringToInt(channel_id.substr(index + 1), secret);
278 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
281 // This case is here to support predictable named pipes in tests.
282 if (secret)
283 *secret = 0;
284 return base::ASCIIToUTF16(name.append(channel_id));
287 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
288 Mode mode) {
289 DCHECK(!pipe_.IsValid());
290 base::string16 pipe_name;
291 // If we already have a valid pipe for channel just copy it.
292 if (channel_handle.pipe.handle) {
293 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
294 // favor of two independent entities (name/file), or it should be a move-
295 // only type with a base::File member. In any case, this code should not
296 // call DuplicateHandle.
297 DCHECK(channel_handle.name.empty());
298 pipe_name = L"Not Available"; // Just used for LOG
299 // Check that the given pipe confirms to the specified mode. We can
300 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
301 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
302 DWORD flags = 0;
303 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
304 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
305 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
306 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
307 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
308 return false;
310 HANDLE local_handle;
311 if (!DuplicateHandle(GetCurrentProcess(),
312 channel_handle.pipe.handle,
313 GetCurrentProcess(),
314 &local_handle,
316 FALSE,
317 DUPLICATE_SAME_ACCESS)) {
318 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
319 return false;
321 pipe_.Set(local_handle);
322 } else if (mode & MODE_SERVER_FLAG) {
323 DCHECK(!channel_handle.pipe.handle);
324 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
325 FILE_FLAG_FIRST_PIPE_INSTANCE;
326 pipe_name = PipeName(channel_handle.name, &client_secret_);
327 validate_client_ = !!client_secret_;
328 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
329 open_mode,
330 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
332 Channel::kReadBufferSize,
333 Channel::kReadBufferSize,
334 5000,
335 NULL));
336 } else if (mode & MODE_CLIENT_FLAG) {
337 DCHECK(!channel_handle.pipe.handle);
338 pipe_name = PipeName(channel_handle.name, &client_secret_);
339 pipe_.Set(CreateFileW(pipe_name.c_str(),
340 GENERIC_READ | GENERIC_WRITE,
342 NULL,
343 OPEN_EXISTING,
344 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
345 FILE_FLAG_OVERLAPPED,
346 NULL));
347 } else {
348 NOTREACHED();
351 if (!pipe_.IsValid()) {
352 // If this process is being closed, the pipe may be gone already.
353 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
354 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
355 return false;
358 // Create the Hello message to be sent when Connect is called
359 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
360 HELLO_MESSAGE_TYPE,
361 IPC::Message::PRIORITY_NORMAL));
363 // Don't send the secret to the untrusted process, and don't send a secret
364 // if the value is zero (for IPC backwards compatability).
365 int32_t secret = validate_client_ ? 0 : client_secret_;
366 if (!m->WriteInt(GetCurrentProcessId()) ||
367 (secret && !m->WriteUInt32(secret))) {
368 pipe_.Close();
369 return false;
372 OutputElement* element = new OutputElement(m.release());
373 output_queue_.push(element);
374 return true;
377 bool ChannelWin::Connect() {
378 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
380 if (!thread_check_.get())
381 thread_check_.reset(new base::ThreadChecker());
383 if (!pipe_.IsValid())
384 return false;
386 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
388 // Check to see if there is a client connected to our pipe...
389 if (waiting_connect_)
390 ProcessConnection();
392 if (!input_state_.is_pending) {
393 // Complete setup asynchronously. By not setting input_state_.is_pending
394 // to true, we indicate to OnIOCompleted that this is the special
395 // initialization signal.
396 base::MessageLoopForIO::current()->PostTask(
397 FROM_HERE,
398 base::Bind(&ChannelWin::OnIOCompleted,
399 weak_factory_.GetWeakPtr(),
400 &input_state_.context,
402 0));
405 if (!waiting_connect_)
406 ProcessOutgoingMessages(NULL, 0);
407 return true;
410 bool ChannelWin::ProcessConnection() {
411 DCHECK(thread_check_->CalledOnValidThread());
412 if (input_state_.is_pending)
413 input_state_.is_pending = false;
415 // Do we have a client connected to our pipe?
416 if (!pipe_.IsValid())
417 return false;
419 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
420 DWORD err = GetLastError();
421 if (ok) {
422 // Uhm, the API documentation says that this function should never
423 // return success when used in overlapped mode.
424 NOTREACHED();
425 return false;
428 switch (err) {
429 case ERROR_IO_PENDING:
430 input_state_.is_pending = true;
431 break;
432 case ERROR_PIPE_CONNECTED:
433 waiting_connect_ = false;
434 break;
435 case ERROR_NO_DATA:
436 // The pipe is being closed.
437 return false;
438 default:
439 NOTREACHED();
440 return false;
443 return true;
446 bool ChannelWin::ProcessOutgoingMessages(
447 base::MessageLoopForIO::IOContext* context,
448 DWORD bytes_written) {
449 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
450 // no connection?
451 DCHECK(thread_check_->CalledOnValidThread());
453 if (output_state_.is_pending) {
454 DCHECK(context);
455 output_state_.is_pending = false;
456 if (!context || bytes_written == 0) {
457 DWORD err = GetLastError();
458 LOG(ERROR) << "pipe error: " << err;
459 return false;
461 // Message was sent.
462 CHECK(!output_queue_.empty());
463 OutputElement* element = output_queue_.front();
464 output_queue_.pop();
465 delete element;
468 if (output_queue_.empty())
469 return true;
471 if (!pipe_.IsValid())
472 return false;
474 // Write to pipe...
475 OutputElement* element = output_queue_.front();
476 DCHECK(element->size() <= INT_MAX);
477 BOOL ok = WriteFile(pipe_.Get(),
478 element->data(),
479 static_cast<uint32_t>(element->size()),
480 NULL,
481 &output_state_.context.overlapped);
482 if (!ok) {
483 DWORD write_error = GetLastError();
484 if (write_error == ERROR_IO_PENDING) {
485 output_state_.is_pending = true;
487 const Message* m = element->get_message();
488 if (m) {
489 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
490 << " with type " << m->type();
493 return true;
495 LOG(ERROR) << "pipe error: " << write_error;
496 return false;
499 const Message* m = element->get_message();
500 if (m) {
501 DVLOG(2) << "sent message @" << m << " on channel @" << this
502 << " with type " << m->type();
505 output_state_.is_pending = true;
506 return true;
509 void ChannelWin::OnIOCompleted(
510 base::MessageLoopForIO::IOContext* context,
511 DWORD bytes_transfered,
512 DWORD error) {
513 bool ok = true;
514 DCHECK(thread_check_->CalledOnValidThread());
515 if (context == &input_state_.context) {
516 if (waiting_connect_) {
517 if (!ProcessConnection())
518 return;
519 // We may have some messages queued up to send...
520 if (!output_queue_.empty() && !output_state_.is_pending)
521 ProcessOutgoingMessages(NULL, 0);
522 if (input_state_.is_pending)
523 return;
524 // else, fall-through and look for incoming messages...
527 // We don't support recursion through OnMessageReceived yet!
528 DCHECK(!processing_incoming_);
529 base::AutoReset<bool> auto_reset_processing_incoming(
530 &processing_incoming_, true);
532 // Process the new data.
533 if (input_state_.is_pending) {
534 // This is the normal case for everything except the initialization step.
535 input_state_.is_pending = false;
536 if (!bytes_transfered) {
537 ok = false;
538 } else if (pipe_.IsValid()) {
539 ok = (AsyncReadComplete(bytes_transfered) != DISPATCH_ERROR);
541 } else {
542 DCHECK(!bytes_transfered);
545 // Request more data.
546 if (ok)
547 ok = (ProcessIncomingMessages() != DISPATCH_ERROR);
548 } else {
549 DCHECK(context == &output_state_.context);
550 CHECK(output_state_.is_pending);
551 ok = ProcessOutgoingMessages(context, bytes_transfered);
553 if (!ok && pipe_.IsValid()) {
554 // We don't want to re-enter Close().
555 Close();
556 listener()->OnChannelError();
560 //------------------------------------------------------------------------------
561 // Channel's methods
563 // static
564 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
565 Mode mode,
566 Listener* listener,
567 AttachmentBroker* broker) {
568 return scoped_ptr<Channel>(
569 new ChannelWin(channel_handle, mode, listener, broker));
572 // static
573 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
574 return ChannelWin::IsNamedServerInitialized(channel_id);
577 // static
578 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
579 // Windows pipes can be enumerated by low-privileged processes. So, we
580 // append a strong random value after the \ character. This value is not
581 // included in the pipe name, but sent as part of the client hello, to
582 // hijacking the pipe name to spoof the client.
584 std::string id = prefix;
585 if (!id.empty())
586 id.append(".");
588 int secret;
589 do { // Guarantee we get a non-zero value.
590 secret = base::RandInt(0, std::numeric_limits<int>::max());
591 } while (secret == 0);
593 id.append(GenerateUniqueRandomChannelID());
594 return id.append(base::StringPrintf("\\%d", secret));
597 } // namespace IPC