Reorder permission message rules, so that related rules appear together.
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blobad7ffb5f62be6cdbd39432819a37ea442d5dfc4e
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 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
124 "ChannelWin::ProcessMessageForDelivery",
125 message->flags(),
126 TRACE_EVENT_FLAG_FLOW_OUT);
128 // |output_queue_| takes ownership of |message|.
129 output_queue_.push(message);
130 // ensure waiting to write
131 if (!waiting_connect_) {
132 if (!output_state_.is_pending) {
133 if (!ProcessOutgoingMessages(NULL, 0))
134 return false;
138 return true;
141 void ChannelWin::FlushPrelimQueue() {
142 DCHECK_NE(peer_pid_, base::kNullProcessId);
144 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
145 // is critical that |prelim_queue_| appears empty.
146 std::queue<Message*> prelim_queue;
147 prelim_queue_.swap(prelim_queue);
149 while (!prelim_queue.empty()) {
150 Message* m = prelim_queue.front();
151 ProcessMessageForDelivery(m);
152 prelim_queue.pop();
156 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
157 return broker_;
160 base::ProcessId ChannelWin::GetPeerPID() const {
161 return peer_pid_;
164 base::ProcessId ChannelWin::GetSelfPID() const {
165 return GetCurrentProcessId();
168 // static
169 bool ChannelWin::IsNamedServerInitialized(
170 const std::string& channel_id) {
171 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
172 return true;
173 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
174 // connection.
175 return GetLastError() == ERROR_SEM_TIMEOUT;
178 ChannelWin::ReadState ChannelWin::ReadData(
179 char* buffer,
180 int buffer_len,
181 int* /* bytes_read */) {
182 if (!pipe_.IsValid())
183 return READ_FAILED;
185 DWORD bytes_read = 0;
186 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
187 &bytes_read, &input_state_.context.overlapped);
188 if (!ok) {
189 DWORD err = GetLastError();
190 if (err == ERROR_IO_PENDING) {
191 input_state_.is_pending = true;
192 return READ_PENDING;
194 LOG(ERROR) << "pipe error: " << err;
195 return READ_FAILED;
198 // We could return READ_SUCCEEDED here. But the way that this code is
199 // structured we instead go back to the message loop. Our completion port
200 // will be signalled even in the "synchronously completed" state.
202 // This allows us to potentially process some outgoing messages and
203 // interleave other work on this thread when we're getting hammered with
204 // input messages. Potentially, this could be tuned to be more efficient
205 // with some testing.
206 input_state_.is_pending = true;
207 return READ_PENDING;
210 bool ChannelWin::ShouldDispatchInputMessage(Message* msg) {
211 // Make sure we get a hello when client validation is required.
212 if (validate_client_)
213 return IsHelloMessage(*msg);
214 return true;
217 bool ChannelWin::GetNonBrokeredAttachments(Message* msg) {
218 return true;
221 void ChannelWin::HandleInternalMessage(const Message& msg) {
222 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
223 // The hello message contains one parameter containing the PID.
224 base::PickleIterator it(msg);
225 int32 claimed_pid;
226 bool failed = !it.ReadInt(&claimed_pid);
228 if (!failed && validate_client_) {
229 int32 secret;
230 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
233 if (failed) {
234 NOTREACHED();
235 Close();
236 listener()->OnChannelError();
237 return;
240 peer_pid_ = claimed_pid;
241 // Validation completed.
242 validate_client_ = false;
244 FlushPrelimQueue();
246 listener()->OnChannelConnected(claimed_pid);
249 base::ProcessId ChannelWin::GetSenderPID() {
250 return GetPeerPID();
253 bool ChannelWin::IsAttachmentBrokerEndpoint() {
254 return is_attachment_broker_endpoint();
257 bool ChannelWin::DidEmptyInputBuffers() {
258 // We don't need to do anything here.
259 return true;
262 // static
263 const base::string16 ChannelWin::PipeName(
264 const std::string& channel_id, int32* secret) {
265 std::string name("\\\\.\\pipe\\chrome.");
267 // Prevent the shared secret from ending up in the pipe name.
268 size_t index = channel_id.find_first_of('\\');
269 if (index != std::string::npos) {
270 if (secret) // Retrieve the secret if asked for.
271 base::StringToInt(channel_id.substr(index + 1), secret);
272 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
275 // This case is here to support predictable named pipes in tests.
276 if (secret)
277 *secret = 0;
278 return base::ASCIIToUTF16(name.append(channel_id));
281 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
282 Mode mode) {
283 DCHECK(!pipe_.IsValid());
284 base::string16 pipe_name;
285 // If we already have a valid pipe for channel just copy it.
286 if (channel_handle.pipe.handle) {
287 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
288 // favor of two independent entities (name/file), or it should be a move-
289 // only type with a base::File member. In any case, this code should not
290 // call DuplicateHandle.
291 DCHECK(channel_handle.name.empty());
292 pipe_name = L"Not Available"; // Just used for LOG
293 // Check that the given pipe confirms to the specified mode. We can
294 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
295 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
296 DWORD flags = 0;
297 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
298 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
299 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
300 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
301 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
302 return false;
304 HANDLE local_handle;
305 if (!DuplicateHandle(GetCurrentProcess(),
306 channel_handle.pipe.handle,
307 GetCurrentProcess(),
308 &local_handle,
310 FALSE,
311 DUPLICATE_SAME_ACCESS)) {
312 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
313 return false;
315 pipe_.Set(local_handle);
316 } else if (mode & MODE_SERVER_FLAG) {
317 DCHECK(!channel_handle.pipe.handle);
318 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
319 FILE_FLAG_FIRST_PIPE_INSTANCE;
320 pipe_name = PipeName(channel_handle.name, &client_secret_);
321 validate_client_ = !!client_secret_;
322 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
323 open_mode,
324 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
326 Channel::kReadBufferSize,
327 Channel::kReadBufferSize,
328 5000,
329 NULL));
330 } else if (mode & MODE_CLIENT_FLAG) {
331 DCHECK(!channel_handle.pipe.handle);
332 pipe_name = PipeName(channel_handle.name, &client_secret_);
333 pipe_.Set(CreateFileW(pipe_name.c_str(),
334 GENERIC_READ | GENERIC_WRITE,
336 NULL,
337 OPEN_EXISTING,
338 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
339 FILE_FLAG_OVERLAPPED,
340 NULL));
341 } else {
342 NOTREACHED();
345 if (!pipe_.IsValid()) {
346 // If this process is being closed, the pipe may be gone already.
347 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
348 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
349 return false;
352 // Create the Hello message to be sent when Connect is called
353 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
354 HELLO_MESSAGE_TYPE,
355 IPC::Message::PRIORITY_NORMAL));
357 // Don't send the secret to the untrusted process, and don't send a secret
358 // if the value is zero (for IPC backwards compatability).
359 int32 secret = validate_client_ ? 0 : client_secret_;
360 if (!m->WriteInt(GetCurrentProcessId()) ||
361 (secret && !m->WriteUInt32(secret))) {
362 pipe_.Close();
363 return false;
366 output_queue_.push(m.release());
367 return true;
370 bool ChannelWin::Connect() {
371 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
373 if (!thread_check_.get())
374 thread_check_.reset(new base::ThreadChecker());
376 if (!pipe_.IsValid())
377 return false;
379 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
381 // Check to see if there is a client connected to our pipe...
382 if (waiting_connect_)
383 ProcessConnection();
385 if (!input_state_.is_pending) {
386 // Complete setup asynchronously. By not setting input_state_.is_pending
387 // to true, we indicate to OnIOCompleted that this is the special
388 // initialization signal.
389 base::MessageLoopForIO::current()->PostTask(
390 FROM_HERE,
391 base::Bind(&ChannelWin::OnIOCompleted,
392 weak_factory_.GetWeakPtr(),
393 &input_state_.context,
395 0));
398 if (!waiting_connect_)
399 ProcessOutgoingMessages(NULL, 0);
400 return true;
403 bool ChannelWin::ProcessConnection() {
404 DCHECK(thread_check_->CalledOnValidThread());
405 if (input_state_.is_pending)
406 input_state_.is_pending = false;
408 // Do we have a client connected to our pipe?
409 if (!pipe_.IsValid())
410 return false;
412 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
413 DWORD err = GetLastError();
414 if (ok) {
415 // Uhm, the API documentation says that this function should never
416 // return success when used in overlapped mode.
417 NOTREACHED();
418 return false;
421 switch (err) {
422 case ERROR_IO_PENDING:
423 input_state_.is_pending = true;
424 break;
425 case ERROR_PIPE_CONNECTED:
426 waiting_connect_ = false;
427 break;
428 case ERROR_NO_DATA:
429 // The pipe is being closed.
430 return false;
431 default:
432 NOTREACHED();
433 return false;
436 return true;
439 bool ChannelWin::ProcessOutgoingMessages(
440 base::MessageLoopForIO::IOContext* context,
441 DWORD bytes_written) {
442 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
443 // no connection?
444 DCHECK(thread_check_->CalledOnValidThread());
446 if (output_state_.is_pending) {
447 DCHECK(context);
448 output_state_.is_pending = false;
449 if (!context || bytes_written == 0) {
450 DWORD err = GetLastError();
451 LOG(ERROR) << "pipe error: " << err;
452 return false;
454 // Message was sent.
455 CHECK(!output_queue_.empty());
456 Message* m = output_queue_.front();
457 output_queue_.pop();
458 delete m;
461 if (output_queue_.empty())
462 return true;
464 if (!pipe_.IsValid())
465 return false;
467 // Write to pipe...
468 Message* m = output_queue_.front();
469 DCHECK(m->size() <= INT_MAX);
470 BOOL ok = WriteFile(pipe_.Get(),
471 m->data(),
472 static_cast<uint32>(m->size()),
473 NULL,
474 &output_state_.context.overlapped);
475 if (!ok) {
476 DWORD write_error = GetLastError();
477 if (write_error == ERROR_IO_PENDING) {
478 output_state_.is_pending = true;
480 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
481 << " with type " << m->type();
483 return true;
485 LOG(ERROR) << "pipe error: " << write_error;
486 return false;
489 DVLOG(2) << "sent message @" << m << " on channel @" << this
490 << " with type " << m->type();
492 output_state_.is_pending = true;
493 return true;
496 void ChannelWin::OnIOCompleted(
497 base::MessageLoopForIO::IOContext* context,
498 DWORD bytes_transfered,
499 DWORD error) {
500 bool ok = true;
501 DCHECK(thread_check_->CalledOnValidThread());
502 if (context == &input_state_.context) {
503 if (waiting_connect_) {
504 if (!ProcessConnection())
505 return;
506 // We may have some messages queued up to send...
507 if (!output_queue_.empty() && !output_state_.is_pending)
508 ProcessOutgoingMessages(NULL, 0);
509 if (input_state_.is_pending)
510 return;
511 // else, fall-through and look for incoming messages...
514 // We don't support recursion through OnMessageReceived yet!
515 DCHECK(!processing_incoming_);
516 base::AutoReset<bool> auto_reset_processing_incoming(
517 &processing_incoming_, true);
519 // Process the new data.
520 if (input_state_.is_pending) {
521 // This is the normal case for everything except the initialization step.
522 input_state_.is_pending = false;
523 if (!bytes_transfered) {
524 ok = false;
525 } else if (pipe_.IsValid()) {
526 ok = (AsyncReadComplete(bytes_transfered) != DISPATCH_ERROR);
528 } else {
529 DCHECK(!bytes_transfered);
532 // Request more data.
533 if (ok)
534 ok = (ProcessIncomingMessages() != DISPATCH_ERROR);
535 } else {
536 DCHECK(context == &output_state_.context);
537 CHECK(output_state_.is_pending);
538 ok = ProcessOutgoingMessages(context, bytes_transfered);
540 if (!ok && pipe_.IsValid()) {
541 // We don't want to re-enter Close().
542 Close();
543 listener()->OnChannelError();
547 //------------------------------------------------------------------------------
548 // Channel's methods
550 // static
551 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
552 Mode mode,
553 Listener* listener,
554 AttachmentBroker* broker) {
555 return scoped_ptr<Channel>(
556 new ChannelWin(channel_handle, mode, listener, broker));
559 // static
560 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
561 return ChannelWin::IsNamedServerInitialized(channel_id);
564 // static
565 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
566 // Windows pipes can be enumerated by low-privileged processes. So, we
567 // append a strong random value after the \ character. This value is not
568 // included in the pipe name, but sent as part of the client hello, to
569 // hijacking the pipe name to spoof the client.
571 std::string id = prefix;
572 if (!id.empty())
573 id.append(".");
575 int secret;
576 do { // Guarantee we get a non-zero value.
577 secret = base::RandInt(0, std::numeric_limits<int>::max());
578 } while (secret == 0);
580 id.append(GenerateUniqueRandomChannelID());
581 return id.append(base::StringPrintf("\\%d", secret));
584 } // namespace IPC