Add ICU message format support
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob1442f7fab7b095392510dbe6509c618c49cbffbc
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 Close();
59 void ChannelWin::Close() {
60 if (thread_check_.get())
61 DCHECK(thread_check_->CalledOnValidThread());
63 if (input_state_.is_pending || output_state_.is_pending)
64 CancelIo(pipe_.Get());
66 // Closing the handle at this point prevents us from issuing more requests
67 // form OnIOCompleted().
68 if (pipe_.IsValid())
69 pipe_.Close();
71 // Make sure all IO has completed.
72 while (input_state_.is_pending || output_state_.is_pending) {
73 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
76 while (!output_queue_.empty()) {
77 Message* m = output_queue_.front();
78 output_queue_.pop();
79 delete m;
83 bool ChannelWin::Send(Message* message) {
84 DCHECK(thread_check_->CalledOnValidThread());
85 DVLOG(2) << "sending message @" << message << " on channel @" << this
86 << " with type " << message->type()
87 << " (" << output_queue_.size() << " in queue)";
89 if (!prelim_queue_.empty()) {
90 prelim_queue_.push(message);
91 return true;
94 if (message->HasBrokerableAttachments() &&
95 peer_pid_ == base::kNullProcessId) {
96 prelim_queue_.push(message);
97 return true;
100 return ProcessMessageForDelivery(message);
103 bool ChannelWin::ProcessMessageForDelivery(Message* message) {
104 // Sending a brokerable attachment requires a call to Channel::Send(), so
105 // both Send() and ProcessMessageForDelivery() may be re-entrant. Brokered
106 // attachments must be sent before the Message itself.
107 if (message->HasBrokerableAttachments()) {
108 DCHECK(broker_);
109 DCHECK(peer_pid_ != base::kNullProcessId);
110 for (const BrokerableAttachment* attachment :
111 message->attachment_set()->PeekBrokerableAttachments()) {
112 if (!broker_->SendAttachmentToProcess(attachment, peer_pid_)) {
113 delete message;
114 return false;
119 #ifdef IPC_MESSAGE_LOG_ENABLED
120 Logging::GetInstance()->OnSendMessage(message, "");
121 #endif
123 message->TraceMessageBegin();
125 // |output_queue_| takes ownership of |message|.
126 output_queue_.push(message);
127 // ensure waiting to write
128 if (!waiting_connect_) {
129 if (!output_state_.is_pending) {
130 if (!ProcessOutgoingMessages(NULL, 0))
131 return false;
135 return true;
138 void ChannelWin::FlushPrelimQueue() {
139 DCHECK_NE(peer_pid_, base::kNullProcessId);
141 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
142 // is critical that |prelim_queue_| appears empty.
143 std::queue<Message*> prelim_queue;
144 prelim_queue_.swap(prelim_queue);
146 while (!prelim_queue.empty()) {
147 Message* m = prelim_queue.front();
148 ProcessMessageForDelivery(m);
149 prelim_queue.pop();
153 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
154 return broker_;
157 base::ProcessId ChannelWin::GetPeerPID() const {
158 return peer_pid_;
161 base::ProcessId ChannelWin::GetSelfPID() const {
162 return GetCurrentProcessId();
165 // static
166 bool ChannelWin::IsNamedServerInitialized(
167 const std::string& channel_id) {
168 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
169 return true;
170 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
171 // connection.
172 return GetLastError() == ERROR_SEM_TIMEOUT;
175 ChannelWin::ReadState ChannelWin::ReadData(
176 char* buffer,
177 int buffer_len,
178 int* /* bytes_read */) {
179 if (!pipe_.IsValid())
180 return READ_FAILED;
182 DWORD bytes_read = 0;
183 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
184 &bytes_read, &input_state_.context.overlapped);
185 if (!ok) {
186 DWORD err = GetLastError();
187 if (err == ERROR_IO_PENDING) {
188 input_state_.is_pending = true;
189 return READ_PENDING;
191 LOG(ERROR) << "pipe error: " << err;
192 return READ_FAILED;
195 // We could return READ_SUCCEEDED here. But the way that this code is
196 // structured we instead go back to the message loop. Our completion port
197 // will be signalled even in the "synchronously completed" state.
199 // This allows us to potentially process some outgoing messages and
200 // interleave other work on this thread when we're getting hammered with
201 // input messages. Potentially, this could be tuned to be more efficient
202 // with some testing.
203 input_state_.is_pending = true;
204 return READ_PENDING;
207 bool ChannelWin::ShouldDispatchInputMessage(Message* msg) {
208 // Make sure we get a hello when client validation is required.
209 if (validate_client_)
210 return IsHelloMessage(*msg);
211 return true;
214 bool ChannelWin::GetNonBrokeredAttachments(Message* msg) {
215 return true;
218 void ChannelWin::HandleInternalMessage(const Message& msg) {
219 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
220 // The hello message contains one parameter containing the PID.
221 base::PickleIterator it(msg);
222 int32 claimed_pid;
223 bool failed = !it.ReadInt(&claimed_pid);
225 if (!failed && validate_client_) {
226 int32 secret;
227 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
230 if (failed) {
231 NOTREACHED();
232 Close();
233 listener()->OnChannelError();
234 return;
237 peer_pid_ = claimed_pid;
238 // Validation completed.
239 validate_client_ = false;
241 FlushPrelimQueue();
243 listener()->OnChannelConnected(claimed_pid);
246 base::ProcessId ChannelWin::GetSenderPID() {
247 return GetPeerPID();
250 bool ChannelWin::IsAttachmentBrokerEndpoint() {
251 return is_attachment_broker_endpoint();
254 bool ChannelWin::DidEmptyInputBuffers() {
255 // We don't need to do anything here.
256 return true;
259 // static
260 const base::string16 ChannelWin::PipeName(
261 const std::string& channel_id, int32* secret) {
262 std::string name("\\\\.\\pipe\\chrome.");
264 // Prevent the shared secret from ending up in the pipe name.
265 size_t index = channel_id.find_first_of('\\');
266 if (index != std::string::npos) {
267 if (secret) // Retrieve the secret if asked for.
268 base::StringToInt(channel_id.substr(index + 1), secret);
269 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
272 // This case is here to support predictable named pipes in tests.
273 if (secret)
274 *secret = 0;
275 return base::ASCIIToUTF16(name.append(channel_id));
278 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
279 Mode mode) {
280 DCHECK(!pipe_.IsValid());
281 base::string16 pipe_name;
282 // If we already have a valid pipe for channel just copy it.
283 if (channel_handle.pipe.handle) {
284 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
285 // favor of two independent entities (name/file), or it should be a move-
286 // only type with a base::File member. In any case, this code should not
287 // call DuplicateHandle.
288 DCHECK(channel_handle.name.empty());
289 pipe_name = L"Not Available"; // Just used for LOG
290 // Check that the given pipe confirms to the specified mode. We can
291 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
292 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
293 DWORD flags = 0;
294 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
295 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
296 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
297 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
298 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
299 return false;
301 HANDLE local_handle;
302 if (!DuplicateHandle(GetCurrentProcess(),
303 channel_handle.pipe.handle,
304 GetCurrentProcess(),
305 &local_handle,
307 FALSE,
308 DUPLICATE_SAME_ACCESS)) {
309 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
310 return false;
312 pipe_.Set(local_handle);
313 } else if (mode & MODE_SERVER_FLAG) {
314 DCHECK(!channel_handle.pipe.handle);
315 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
316 FILE_FLAG_FIRST_PIPE_INSTANCE;
317 pipe_name = PipeName(channel_handle.name, &client_secret_);
318 validate_client_ = !!client_secret_;
319 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
320 open_mode,
321 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
323 Channel::kReadBufferSize,
324 Channel::kReadBufferSize,
325 5000,
326 NULL));
327 } else if (mode & MODE_CLIENT_FLAG) {
328 DCHECK(!channel_handle.pipe.handle);
329 pipe_name = PipeName(channel_handle.name, &client_secret_);
330 pipe_.Set(CreateFileW(pipe_name.c_str(),
331 GENERIC_READ | GENERIC_WRITE,
333 NULL,
334 OPEN_EXISTING,
335 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
336 FILE_FLAG_OVERLAPPED,
337 NULL));
338 } else {
339 NOTREACHED();
342 if (!pipe_.IsValid()) {
343 // If this process is being closed, the pipe may be gone already.
344 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
345 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
346 return false;
349 // Create the Hello message to be sent when Connect is called
350 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
351 HELLO_MESSAGE_TYPE,
352 IPC::Message::PRIORITY_NORMAL));
354 // Don't send the secret to the untrusted process, and don't send a secret
355 // if the value is zero (for IPC backwards compatability).
356 int32 secret = validate_client_ ? 0 : client_secret_;
357 if (!m->WriteInt(GetCurrentProcessId()) ||
358 (secret && !m->WriteUInt32(secret))) {
359 pipe_.Close();
360 return false;
363 output_queue_.push(m.release());
364 return true;
367 bool ChannelWin::Connect() {
368 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
370 if (!thread_check_.get())
371 thread_check_.reset(new base::ThreadChecker());
373 if (!pipe_.IsValid())
374 return false;
376 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
378 // Check to see if there is a client connected to our pipe...
379 if (waiting_connect_)
380 ProcessConnection();
382 if (!input_state_.is_pending) {
383 // Complete setup asynchronously. By not setting input_state_.is_pending
384 // to true, we indicate to OnIOCompleted that this is the special
385 // initialization signal.
386 base::MessageLoopForIO::current()->PostTask(
387 FROM_HERE,
388 base::Bind(&ChannelWin::OnIOCompleted,
389 weak_factory_.GetWeakPtr(),
390 &input_state_.context,
392 0));
395 if (!waiting_connect_)
396 ProcessOutgoingMessages(NULL, 0);
397 return true;
400 bool ChannelWin::ProcessConnection() {
401 DCHECK(thread_check_->CalledOnValidThread());
402 if (input_state_.is_pending)
403 input_state_.is_pending = false;
405 // Do we have a client connected to our pipe?
406 if (!pipe_.IsValid())
407 return false;
409 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
410 DWORD err = GetLastError();
411 if (ok) {
412 // Uhm, the API documentation says that this function should never
413 // return success when used in overlapped mode.
414 NOTREACHED();
415 return false;
418 switch (err) {
419 case ERROR_IO_PENDING:
420 input_state_.is_pending = true;
421 break;
422 case ERROR_PIPE_CONNECTED:
423 waiting_connect_ = false;
424 break;
425 case ERROR_NO_DATA:
426 // The pipe is being closed.
427 return false;
428 default:
429 NOTREACHED();
430 return false;
433 return true;
436 bool ChannelWin::ProcessOutgoingMessages(
437 base::MessageLoopForIO::IOContext* context,
438 DWORD bytes_written) {
439 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
440 // no connection?
441 DCHECK(thread_check_->CalledOnValidThread());
443 if (output_state_.is_pending) {
444 DCHECK(context);
445 output_state_.is_pending = false;
446 if (!context || bytes_written == 0) {
447 DWORD err = GetLastError();
448 LOG(ERROR) << "pipe error: " << err;
449 return false;
451 // Message was sent.
452 CHECK(!output_queue_.empty());
453 Message* m = output_queue_.front();
454 output_queue_.pop();
455 delete m;
458 if (output_queue_.empty())
459 return true;
461 if (!pipe_.IsValid())
462 return false;
464 // Write to pipe...
465 Message* m = output_queue_.front();
466 DCHECK(m->size() <= INT_MAX);
467 BOOL ok = WriteFile(pipe_.Get(),
468 m->data(),
469 static_cast<uint32>(m->size()),
470 NULL,
471 &output_state_.context.overlapped);
472 if (!ok) {
473 DWORD write_error = GetLastError();
474 if (write_error == ERROR_IO_PENDING) {
475 output_state_.is_pending = true;
477 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
478 << " with type " << m->type();
480 return true;
482 LOG(ERROR) << "pipe error: " << write_error;
483 return false;
486 DVLOG(2) << "sent message @" << m << " on channel @" << this
487 << " with type " << m->type();
489 output_state_.is_pending = true;
490 return true;
493 void ChannelWin::OnIOCompleted(
494 base::MessageLoopForIO::IOContext* context,
495 DWORD bytes_transfered,
496 DWORD error) {
497 bool ok = true;
498 DCHECK(thread_check_->CalledOnValidThread());
499 if (context == &input_state_.context) {
500 if (waiting_connect_) {
501 if (!ProcessConnection())
502 return;
503 // We may have some messages queued up to send...
504 if (!output_queue_.empty() && !output_state_.is_pending)
505 ProcessOutgoingMessages(NULL, 0);
506 if (input_state_.is_pending)
507 return;
508 // else, fall-through and look for incoming messages...
511 // We don't support recursion through OnMessageReceived yet!
512 DCHECK(!processing_incoming_);
513 base::AutoReset<bool> auto_reset_processing_incoming(
514 &processing_incoming_, true);
516 // Process the new data.
517 if (input_state_.is_pending) {
518 // This is the normal case for everything except the initialization step.
519 input_state_.is_pending = false;
520 if (!bytes_transfered) {
521 ok = false;
522 } else if (pipe_.IsValid()) {
523 ok = (AsyncReadComplete(bytes_transfered) != DISPATCH_ERROR);
525 } else {
526 DCHECK(!bytes_transfered);
529 // Request more data.
530 if (ok)
531 ok = (ProcessIncomingMessages() != DISPATCH_ERROR);
532 } else {
533 DCHECK(context == &output_state_.context);
534 CHECK(output_state_.is_pending);
535 ok = ProcessOutgoingMessages(context, bytes_transfered);
537 if (!ok && pipe_.IsValid()) {
538 // We don't want to re-enter Close().
539 Close();
540 listener()->OnChannelError();
544 //------------------------------------------------------------------------------
545 // Channel's methods
547 // static
548 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
549 Mode mode,
550 Listener* listener,
551 AttachmentBroker* broker) {
552 return scoped_ptr<Channel>(
553 new ChannelWin(channel_handle, mode, listener, broker));
556 // static
557 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
558 return ChannelWin::IsNamedServerInitialized(channel_id);
561 // static
562 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
563 // Windows pipes can be enumerated by low-privileged processes. So, we
564 // append a strong random value after the \ character. This value is not
565 // included in the pipe name, but sent as part of the client hello, to
566 // hijacking the pipe name to spoof the client.
568 std::string id = prefix;
569 if (!id.empty())
570 id.append(".");
572 int secret;
573 do { // Guarantee we get a non-zero value.
574 secret = base::RandInt(0, std::numeric_limits<int>::max());
575 } while (secret == 0);
577 id.append(GenerateUniqueRandomChannelID());
578 return id.append(base::StringPrintf("\\%d", secret));
581 } // namespace IPC