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"
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_utils.h"
26 ChannelWin::State::State(ChannelWin
* channel
) : is_pending(false) {
27 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
28 context
.handler
= channel
;
31 ChannelWin::State::~State() {
32 static_assert(offsetof(ChannelWin::State
, context
) == 0,
33 "ChannelWin::State should have context as its first data"
37 ChannelWin::ChannelWin(const IPC::ChannelHandle
&channel_handle
,
38 Mode mode
, Listener
* listener
)
39 : ChannelReader(listener
),
42 peer_pid_(base::kNullProcessId
),
43 waiting_connect_(mode
& MODE_SERVER_FLAG
),
44 processing_incoming_(false),
45 validate_client_(false),
48 CreatePipe(channel_handle
, mode
);
51 ChannelWin::~ChannelWin() {
55 void ChannelWin::Close() {
56 if (thread_check_
.get())
57 DCHECK(thread_check_
->CalledOnValidThread());
59 if (input_state_
.is_pending
|| output_state_
.is_pending
)
60 CancelIo(pipe_
.Get());
62 // Closing the handle at this point prevents us from issuing more requests
63 // form OnIOCompleted().
67 // Make sure all IO has completed.
68 base::Time start
= base::Time::Now();
69 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
70 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
73 while (!output_queue_
.empty()) {
74 Message
* m
= output_queue_
.front();
80 bool ChannelWin::Send(Message
* message
) {
81 DCHECK(thread_check_
->CalledOnValidThread());
82 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
83 << " with type " << message
->type()
84 << " (" << output_queue_
.size() << " in queue)";
86 #ifdef IPC_MESSAGE_LOG_ENABLED
87 Logging::GetInstance()->OnSendMessage(message
, "");
90 message
->TraceMessageBegin();
91 output_queue_
.push(message
);
92 // ensure waiting to write
93 if (!waiting_connect_
) {
94 if (!output_state_
.is_pending
) {
95 if (!ProcessOutgoingMessages(NULL
, 0))
103 base::ProcessId
ChannelWin::GetPeerPID() const {
107 base::ProcessId
ChannelWin::GetSelfPID() const {
108 return GetCurrentProcessId();
112 bool ChannelWin::IsNamedServerInitialized(
113 const std::string
& channel_id
) {
114 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
116 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
118 return GetLastError() == ERROR_SEM_TIMEOUT
;
121 ChannelWin::ReadState
ChannelWin::ReadData(
124 int* /* bytes_read */) {
125 if (!pipe_
.IsValid())
128 DWORD bytes_read
= 0;
129 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
130 &bytes_read
, &input_state_
.context
.overlapped
);
132 DWORD err
= GetLastError();
133 if (err
== ERROR_IO_PENDING
) {
134 input_state_
.is_pending
= true;
137 LOG(ERROR
) << "pipe error: " << err
;
141 // We could return READ_SUCCEEDED here. But the way that this code is
142 // structured we instead go back to the message loop. Our completion port
143 // will be signalled even in the "synchronously completed" state.
145 // This allows us to potentially process some outgoing messages and
146 // interleave other work on this thread when we're getting hammered with
147 // input messages. Potentially, this could be tuned to be more efficient
148 // with some testing.
149 input_state_
.is_pending
= true;
153 bool ChannelWin::WillDispatchInputMessage(Message
* msg
) {
154 // Make sure we get a hello when client validation is required.
155 if (validate_client_
)
156 return IsHelloMessage(*msg
);
160 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
161 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
162 // The hello message contains one parameter containing the PID.
163 PickleIterator
it(msg
);
165 bool failed
= !it
.ReadInt(&claimed_pid
);
167 if (!failed
&& validate_client_
) {
169 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
175 listener()->OnChannelError();
179 peer_pid_
= claimed_pid
;
180 // Validation completed.
181 validate_client_
= false;
182 listener()->OnChannelConnected(claimed_pid
);
185 bool ChannelWin::DidEmptyInputBuffers() {
186 // We don't need to do anything here.
191 const base::string16
ChannelWin::PipeName(
192 const std::string
& channel_id
, int32
* secret
) {
193 std::string
name("\\\\.\\pipe\\chrome.");
195 // Prevent the shared secret from ending up in the pipe name.
196 size_t index
= channel_id
.find_first_of('\\');
197 if (index
!= std::string::npos
) {
198 if (secret
) // Retrieve the secret if asked for.
199 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
200 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
203 // This case is here to support predictable named pipes in tests.
206 return base::ASCIIToUTF16(name
.append(channel_id
));
209 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
211 DCHECK(!pipe_
.IsValid());
212 base::string16 pipe_name
;
213 // If we already have a valid pipe for channel just copy it.
214 if (channel_handle
.pipe
.handle
) {
215 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
216 // favor of two independent entities (name/file), or it should be a move-
217 // only type with a base::File member. In any case, this code should not
218 // call DuplicateHandle.
219 DCHECK(channel_handle
.name
.empty());
220 pipe_name
= L
"Not Available"; // Just used for LOG
221 // Check that the given pipe confirms to the specified mode. We can
222 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
223 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
225 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
226 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
227 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
228 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
229 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
233 if (!DuplicateHandle(GetCurrentProcess(),
234 channel_handle
.pipe
.handle
,
239 DUPLICATE_SAME_ACCESS
)) {
240 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
243 pipe_
.Set(local_handle
);
244 } else if (mode
& MODE_SERVER_FLAG
) {
245 DCHECK(!channel_handle
.pipe
.handle
);
246 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
247 FILE_FLAG_FIRST_PIPE_INSTANCE
;
248 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
249 validate_client_
= !!client_secret_
;
250 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
252 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
254 Channel::kReadBufferSize
,
255 Channel::kReadBufferSize
,
258 } else if (mode
& MODE_CLIENT_FLAG
) {
259 DCHECK(!channel_handle
.pipe
.handle
);
260 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
261 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
262 GENERIC_READ
| GENERIC_WRITE
,
266 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
267 FILE_FLAG_OVERLAPPED
,
273 if (!pipe_
.IsValid()) {
274 // If this process is being closed, the pipe may be gone already.
275 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
276 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
280 // Create the Hello message to be sent when Connect is called
281 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
283 IPC::Message::PRIORITY_NORMAL
));
285 // Don't send the secret to the untrusted process, and don't send a secret
286 // if the value is zero (for IPC backwards compatability).
287 int32 secret
= validate_client_
? 0 : client_secret_
;
288 if (!m
->WriteInt(GetCurrentProcessId()) ||
289 (secret
&& !m
->WriteUInt32(secret
))) {
294 output_queue_
.push(m
.release());
298 bool ChannelWin::Connect() {
299 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
301 if (!thread_check_
.get())
302 thread_check_
.reset(new base::ThreadChecker());
304 if (!pipe_
.IsValid())
307 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
309 // Check to see if there is a client connected to our pipe...
310 if (waiting_connect_
)
313 if (!input_state_
.is_pending
) {
314 // Complete setup asynchronously. By not setting input_state_.is_pending
315 // to true, we indicate to OnIOCompleted that this is the special
316 // initialization signal.
317 base::MessageLoopForIO::current()->PostTask(
319 base::Bind(&ChannelWin::OnIOCompleted
,
320 weak_factory_
.GetWeakPtr(),
321 &input_state_
.context
,
326 if (!waiting_connect_
)
327 ProcessOutgoingMessages(NULL
, 0);
331 bool ChannelWin::ProcessConnection() {
332 DCHECK(thread_check_
->CalledOnValidThread());
333 if (input_state_
.is_pending
)
334 input_state_
.is_pending
= false;
336 // Do we have a client connected to our pipe?
337 if (!pipe_
.IsValid())
340 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
341 DWORD err
= GetLastError();
343 // Uhm, the API documentation says that this function should never
344 // return success when used in overlapped mode.
350 case ERROR_IO_PENDING
:
351 input_state_
.is_pending
= true;
353 case ERROR_PIPE_CONNECTED
:
354 waiting_connect_
= false;
357 // The pipe is being closed.
367 bool ChannelWin::ProcessOutgoingMessages(
368 base::MessageLoopForIO::IOContext
* context
,
369 DWORD bytes_written
) {
370 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
372 DCHECK(thread_check_
->CalledOnValidThread());
374 if (output_state_
.is_pending
) {
376 output_state_
.is_pending
= false;
377 if (!context
|| bytes_written
== 0) {
378 DWORD err
= GetLastError();
379 LOG(ERROR
) << "pipe error: " << err
;
383 CHECK(!output_queue_
.empty());
384 Message
* m
= output_queue_
.front();
389 if (output_queue_
.empty())
392 if (!pipe_
.IsValid())
396 Message
* m
= output_queue_
.front();
397 DCHECK(m
->size() <= INT_MAX
);
398 BOOL ok
= WriteFile(pipe_
.Get(),
400 static_cast<uint32
>(m
->size()),
402 &output_state_
.context
.overlapped
);
404 DWORD write_error
= GetLastError();
405 if (write_error
== ERROR_IO_PENDING
) {
406 output_state_
.is_pending
= true;
408 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
409 << " with type " << m
->type();
413 LOG(ERROR
) << "pipe error: " << write_error
;
417 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
418 << " with type " << m
->type();
420 output_state_
.is_pending
= true;
424 void ChannelWin::OnIOCompleted(
425 base::MessageLoopForIO::IOContext
* context
,
426 DWORD bytes_transfered
,
429 DCHECK(thread_check_
->CalledOnValidThread());
430 if (context
== &input_state_
.context
) {
431 if (waiting_connect_
) {
432 if (!ProcessConnection())
434 // We may have some messages queued up to send...
435 if (!output_queue_
.empty() && !output_state_
.is_pending
)
436 ProcessOutgoingMessages(NULL
, 0);
437 if (input_state_
.is_pending
)
439 // else, fall-through and look for incoming messages...
442 // We don't support recursion through OnMessageReceived yet!
443 DCHECK(!processing_incoming_
);
444 base::AutoReset
<bool> auto_reset_processing_incoming(
445 &processing_incoming_
, true);
447 // Process the new data.
448 if (input_state_
.is_pending
) {
449 // This is the normal case for everything except the initialization step.
450 input_state_
.is_pending
= false;
451 if (!bytes_transfered
)
453 else if (pipe_
.IsValid())
454 ok
= AsyncReadComplete(bytes_transfered
);
456 DCHECK(!bytes_transfered
);
459 // Request more data.
461 ok
= ProcessIncomingMessages();
463 DCHECK(context
== &output_state_
.context
);
464 CHECK(output_state_
.is_pending
);
465 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
467 if (!ok
&& pipe_
.IsValid()) {
468 // We don't want to re-enter Close().
470 listener()->OnChannelError();
474 //------------------------------------------------------------------------------
478 scoped_ptr
<Channel
> Channel::Create(
479 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
480 return scoped_ptr
<Channel
>(
481 new ChannelWin(channel_handle
, mode
, listener
));
485 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
486 return ChannelWin::IsNamedServerInitialized(channel_id
);
490 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
491 // Windows pipes can be enumerated by low-privileged processes. So, we
492 // append a strong random value after the \ character. This value is not
493 // included in the pipe name, but sent as part of the client hello, to
494 // hijacking the pipe name to spoof the client.
496 std::string id
= prefix
;
501 do { // Guarantee we get a non-zero value.
502 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
503 } while (secret
== 0);
505 id
.append(GenerateUniqueRandomChannelID());
506 return id
.append(base::StringPrintf("\\%d", secret
));