Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
blob05b9475a3487a627b196badd389e9a39a48a2b67
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 // TODO(erikchen): Remove this DCHECK once ChannelWin fully supports
85 // brokerable attachments. http://crbug.com/493414.
86 DCHECK(!message->HasAttachments());
87 DCHECK(thread_check_->CalledOnValidThread());
88 DVLOG(2) << "sending message @" << message << " on channel @" << this
89 << " with type " << message->type()
90 << " (" << output_queue_.size() << " in queue)";
92 // Sending a brokerable attachment requires a call to Channel::Send(), so
93 // Send() may be re-entrant. Brokered attachments must be sent before the
94 // Message itself.
95 if (message->HasBrokerableAttachments()) {
96 DCHECK(broker_);
97 for (const BrokerableAttachment* attachment :
98 message->attachment_set()->PeekBrokerableAttachments()) {
99 if (!broker_->SendAttachmentToProcess(attachment, peer_pid_))
100 return false;
104 #ifdef IPC_MESSAGE_LOG_ENABLED
105 Logging::GetInstance()->OnSendMessage(message, "");
106 #endif
108 message->TraceMessageBegin();
109 output_queue_.push(message);
110 // ensure waiting to write
111 if (!waiting_connect_) {
112 if (!output_state_.is_pending) {
113 if (!ProcessOutgoingMessages(NULL, 0))
114 return false;
118 return true;
121 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
122 return broker_;
125 base::ProcessId ChannelWin::GetPeerPID() const {
126 return peer_pid_;
129 base::ProcessId ChannelWin::GetSelfPID() const {
130 return GetCurrentProcessId();
133 // static
134 bool ChannelWin::IsNamedServerInitialized(
135 const std::string& channel_id) {
136 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
137 return true;
138 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
139 // connection.
140 return GetLastError() == ERROR_SEM_TIMEOUT;
143 ChannelWin::ReadState ChannelWin::ReadData(
144 char* buffer,
145 int buffer_len,
146 int* /* bytes_read */) {
147 if (!pipe_.IsValid())
148 return READ_FAILED;
150 DWORD bytes_read = 0;
151 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
152 &bytes_read, &input_state_.context.overlapped);
153 if (!ok) {
154 DWORD err = GetLastError();
155 if (err == ERROR_IO_PENDING) {
156 input_state_.is_pending = true;
157 return READ_PENDING;
159 LOG(ERROR) << "pipe error: " << err;
160 return READ_FAILED;
163 // We could return READ_SUCCEEDED here. But the way that this code is
164 // structured we instead go back to the message loop. Our completion port
165 // will be signalled even in the "synchronously completed" state.
167 // This allows us to potentially process some outgoing messages and
168 // interleave other work on this thread when we're getting hammered with
169 // input messages. Potentially, this could be tuned to be more efficient
170 // with some testing.
171 input_state_.is_pending = true;
172 return READ_PENDING;
175 bool ChannelWin::WillDispatchInputMessage(Message* msg) {
176 // Make sure we get a hello when client validation is required.
177 if (validate_client_)
178 return IsHelloMessage(*msg);
179 return true;
182 void ChannelWin::HandleInternalMessage(const Message& msg) {
183 DCHECK_EQ(msg.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE));
184 // The hello message contains one parameter containing the PID.
185 base::PickleIterator it(msg);
186 int32 claimed_pid;
187 bool failed = !it.ReadInt(&claimed_pid);
189 if (!failed && validate_client_) {
190 int32 secret;
191 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
194 if (failed) {
195 NOTREACHED();
196 Close();
197 listener()->OnChannelError();
198 return;
201 peer_pid_ = claimed_pid;
202 // Validation completed.
203 validate_client_ = false;
204 listener()->OnChannelConnected(claimed_pid);
207 bool ChannelWin::DidEmptyInputBuffers() {
208 // We don't need to do anything here.
209 return true;
212 // static
213 const base::string16 ChannelWin::PipeName(
214 const std::string& channel_id, int32* secret) {
215 std::string name("\\\\.\\pipe\\chrome.");
217 // Prevent the shared secret from ending up in the pipe name.
218 size_t index = channel_id.find_first_of('\\');
219 if (index != std::string::npos) {
220 if (secret) // Retrieve the secret if asked for.
221 base::StringToInt(channel_id.substr(index + 1), secret);
222 return base::ASCIIToUTF16(name.append(channel_id.substr(0, index - 1)));
225 // This case is here to support predictable named pipes in tests.
226 if (secret)
227 *secret = 0;
228 return base::ASCIIToUTF16(name.append(channel_id));
231 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
232 Mode mode) {
233 DCHECK(!pipe_.IsValid());
234 base::string16 pipe_name;
235 // If we already have a valid pipe for channel just copy it.
236 if (channel_handle.pipe.handle) {
237 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
238 // favor of two independent entities (name/file), or it should be a move-
239 // only type with a base::File member. In any case, this code should not
240 // call DuplicateHandle.
241 DCHECK(channel_handle.name.empty());
242 pipe_name = L"Not Available"; // Just used for LOG
243 // Check that the given pipe confirms to the specified mode. We can
244 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
245 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
246 DWORD flags = 0;
247 GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL);
248 DCHECK(!(flags & PIPE_TYPE_MESSAGE));
249 if (((mode & MODE_SERVER_FLAG) && !(flags & PIPE_SERVER_END)) ||
250 ((mode & MODE_CLIENT_FLAG) && (flags & PIPE_SERVER_END))) {
251 LOG(WARNING) << "Inconsistent open mode. Mode :" << mode;
252 return false;
254 HANDLE local_handle;
255 if (!DuplicateHandle(GetCurrentProcess(),
256 channel_handle.pipe.handle,
257 GetCurrentProcess(),
258 &local_handle,
260 FALSE,
261 DUPLICATE_SAME_ACCESS)) {
262 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
263 return false;
265 pipe_.Set(local_handle);
266 } else if (mode & MODE_SERVER_FLAG) {
267 DCHECK(!channel_handle.pipe.handle);
268 const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED |
269 FILE_FLAG_FIRST_PIPE_INSTANCE;
270 pipe_name = PipeName(channel_handle.name, &client_secret_);
271 validate_client_ = !!client_secret_;
272 pipe_.Set(CreateNamedPipeW(pipe_name.c_str(),
273 open_mode,
274 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
276 Channel::kReadBufferSize,
277 Channel::kReadBufferSize,
278 5000,
279 NULL));
280 } else if (mode & MODE_CLIENT_FLAG) {
281 DCHECK(!channel_handle.pipe.handle);
282 pipe_name = PipeName(channel_handle.name, &client_secret_);
283 pipe_.Set(CreateFileW(pipe_name.c_str(),
284 GENERIC_READ | GENERIC_WRITE,
286 NULL,
287 OPEN_EXISTING,
288 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
289 FILE_FLAG_OVERLAPPED,
290 NULL));
291 } else {
292 NOTREACHED();
295 if (!pipe_.IsValid()) {
296 // If this process is being closed, the pipe may be gone already.
297 PLOG(WARNING) << "Unable to create pipe \"" << pipe_name << "\" in "
298 << (mode & MODE_SERVER_FLAG ? "server" : "client") << " mode";
299 return false;
302 // Create the Hello message to be sent when Connect is called
303 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
304 HELLO_MESSAGE_TYPE,
305 IPC::Message::PRIORITY_NORMAL));
307 // Don't send the secret to the untrusted process, and don't send a secret
308 // if the value is zero (for IPC backwards compatability).
309 int32 secret = validate_client_ ? 0 : client_secret_;
310 if (!m->WriteInt(GetCurrentProcessId()) ||
311 (secret && !m->WriteUInt32(secret))) {
312 pipe_.Close();
313 return false;
316 output_queue_.push(m.release());
317 return true;
320 bool ChannelWin::Connect() {
321 DLOG_IF(WARNING, thread_check_.get()) << "Connect called more than once";
323 if (!thread_check_.get())
324 thread_check_.reset(new base::ThreadChecker());
326 if (!pipe_.IsValid())
327 return false;
329 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_.Get(), this);
331 // Check to see if there is a client connected to our pipe...
332 if (waiting_connect_)
333 ProcessConnection();
335 if (!input_state_.is_pending) {
336 // Complete setup asynchronously. By not setting input_state_.is_pending
337 // to true, we indicate to OnIOCompleted that this is the special
338 // initialization signal.
339 base::MessageLoopForIO::current()->PostTask(
340 FROM_HERE,
341 base::Bind(&ChannelWin::OnIOCompleted,
342 weak_factory_.GetWeakPtr(),
343 &input_state_.context,
345 0));
348 if (!waiting_connect_)
349 ProcessOutgoingMessages(NULL, 0);
350 return true;
353 bool ChannelWin::ProcessConnection() {
354 DCHECK(thread_check_->CalledOnValidThread());
355 if (input_state_.is_pending)
356 input_state_.is_pending = false;
358 // Do we have a client connected to our pipe?
359 if (!pipe_.IsValid())
360 return false;
362 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
363 DWORD err = GetLastError();
364 if (ok) {
365 // Uhm, the API documentation says that this function should never
366 // return success when used in overlapped mode.
367 NOTREACHED();
368 return false;
371 switch (err) {
372 case ERROR_IO_PENDING:
373 input_state_.is_pending = true;
374 break;
375 case ERROR_PIPE_CONNECTED:
376 waiting_connect_ = false;
377 break;
378 case ERROR_NO_DATA:
379 // The pipe is being closed.
380 return false;
381 default:
382 NOTREACHED();
383 return false;
386 return true;
389 bool ChannelWin::ProcessOutgoingMessages(
390 base::MessageLoopForIO::IOContext* context,
391 DWORD bytes_written) {
392 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
393 // no connection?
394 DCHECK(thread_check_->CalledOnValidThread());
396 if (output_state_.is_pending) {
397 DCHECK(context);
398 output_state_.is_pending = false;
399 if (!context || bytes_written == 0) {
400 DWORD err = GetLastError();
401 LOG(ERROR) << "pipe error: " << err;
402 return false;
404 // Message was sent.
405 CHECK(!output_queue_.empty());
406 Message* m = output_queue_.front();
407 output_queue_.pop();
408 delete m;
411 if (output_queue_.empty())
412 return true;
414 if (!pipe_.IsValid())
415 return false;
417 // Write to pipe...
418 Message* m = output_queue_.front();
419 DCHECK(m->size() <= INT_MAX);
420 BOOL ok = WriteFile(pipe_.Get(),
421 m->data(),
422 static_cast<uint32>(m->size()),
423 NULL,
424 &output_state_.context.overlapped);
425 if (!ok) {
426 DWORD write_error = GetLastError();
427 if (write_error == ERROR_IO_PENDING) {
428 output_state_.is_pending = true;
430 DVLOG(2) << "sent pending message @" << m << " on channel @" << this
431 << " with type " << m->type();
433 return true;
435 LOG(ERROR) << "pipe error: " << write_error;
436 return false;
439 DVLOG(2) << "sent message @" << m << " on channel @" << this
440 << " with type " << m->type();
442 output_state_.is_pending = true;
443 return true;
446 void ChannelWin::OnIOCompleted(
447 base::MessageLoopForIO::IOContext* context,
448 DWORD bytes_transfered,
449 DWORD error) {
450 bool ok = true;
451 DCHECK(thread_check_->CalledOnValidThread());
452 if (context == &input_state_.context) {
453 if (waiting_connect_) {
454 if (!ProcessConnection())
455 return;
456 // We may have some messages queued up to send...
457 if (!output_queue_.empty() && !output_state_.is_pending)
458 ProcessOutgoingMessages(NULL, 0);
459 if (input_state_.is_pending)
460 return;
461 // else, fall-through and look for incoming messages...
464 // We don't support recursion through OnMessageReceived yet!
465 DCHECK(!processing_incoming_);
466 base::AutoReset<bool> auto_reset_processing_incoming(
467 &processing_incoming_, true);
469 // Process the new data.
470 if (input_state_.is_pending) {
471 // This is the normal case for everything except the initialization step.
472 input_state_.is_pending = false;
473 if (!bytes_transfered)
474 ok = false;
475 else if (pipe_.IsValid())
476 ok = AsyncReadComplete(bytes_transfered);
477 } else {
478 DCHECK(!bytes_transfered);
481 // Request more data.
482 if (ok)
483 ok = ProcessIncomingMessages();
484 } else {
485 DCHECK(context == &output_state_.context);
486 CHECK(output_state_.is_pending);
487 ok = ProcessOutgoingMessages(context, bytes_transfered);
489 if (!ok && pipe_.IsValid()) {
490 // We don't want to re-enter Close().
491 Close();
492 listener()->OnChannelError();
496 //------------------------------------------------------------------------------
497 // Channel's methods
499 // static
500 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
501 Mode mode,
502 Listener* listener,
503 AttachmentBroker* broker) {
504 return scoped_ptr<Channel>(
505 new ChannelWin(channel_handle, mode, listener, broker));
508 // static
509 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
510 return ChannelWin::IsNamedServerInitialized(channel_id);
513 // static
514 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
515 // Windows pipes can be enumerated by low-privileged processes. So, we
516 // append a strong random value after the \ character. This value is not
517 // included in the pipe name, but sent as part of the client hello, to
518 // hijacking the pipe name to spoof the client.
520 std::string id = prefix;
521 if (!id.empty())
522 id.append(".");
524 int secret;
525 do { // Guarantee we get a non-zero value.
526 secret = base::RandInt(0, std::numeric_limits<int>::max());
527 } while (secret == 0);
529 id.append(GenerateUniqueRandomChannelID());
530 return id.append(base::StringPrintf("\\%d", secret));
533 } // namespace IPC