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 COMPILE_ASSERT(!offsetof(ChannelWin::State
, context
),
33 starts_with_io_context
);
36 ChannelWin::ChannelWin(const IPC::ChannelHandle
&channel_handle
,
37 Mode mode
, Listener
* listener
)
38 : ChannelReader(listener
),
41 peer_pid_(base::kNullProcessId
),
42 waiting_connect_(mode
& MODE_SERVER_FLAG
),
43 processing_incoming_(false),
44 validate_client_(false),
47 CreatePipe(channel_handle
, mode
);
50 ChannelWin::~ChannelWin() {
54 void ChannelWin::Close() {
55 if (thread_check_
.get())
56 DCHECK(thread_check_
->CalledOnValidThread());
58 if (input_state_
.is_pending
|| output_state_
.is_pending
)
59 CancelIo(pipe_
.Get());
61 // Closing the handle at this point prevents us from issuing more requests
62 // form OnIOCompleted().
66 // Make sure all IO has completed.
67 base::Time start
= base::Time::Now();
68 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
69 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
72 while (!output_queue_
.empty()) {
73 Message
* m
= output_queue_
.front();
79 bool ChannelWin::Send(Message
* message
) {
80 DCHECK(thread_check_
->CalledOnValidThread());
81 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
82 << " with type " << message
->type()
83 << " (" << output_queue_
.size() << " in queue)";
85 #ifdef IPC_MESSAGE_LOG_ENABLED
86 Logging::GetInstance()->OnSendMessage(message
, "");
89 message
->TraceMessageBegin();
90 output_queue_
.push(message
);
91 // ensure waiting to write
92 if (!waiting_connect_
) {
93 if (!output_state_
.is_pending
) {
94 if (!ProcessOutgoingMessages(NULL
, 0))
102 base::ProcessId
ChannelWin::GetPeerPID() const {
106 base::ProcessId
ChannelWin::GetSelfPID() const {
107 return GetCurrentProcessId();
111 bool ChannelWin::IsNamedServerInitialized(
112 const std::string
& channel_id
) {
113 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
115 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
117 return GetLastError() == ERROR_SEM_TIMEOUT
;
120 ChannelWin::ReadState
ChannelWin::ReadData(
123 int* /* bytes_read */) {
124 if (!pipe_
.IsValid())
127 DWORD bytes_read
= 0;
128 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
129 &bytes_read
, &input_state_
.context
.overlapped
);
131 DWORD err
= GetLastError();
132 if (err
== ERROR_IO_PENDING
) {
133 input_state_
.is_pending
= true;
136 LOG(ERROR
) << "pipe error: " << err
;
140 // We could return READ_SUCCEEDED here. But the way that this code is
141 // structured we instead go back to the message loop. Our completion port
142 // will be signalled even in the "synchronously completed" state.
144 // This allows us to potentially process some outgoing messages and
145 // interleave other work on this thread when we're getting hammered with
146 // input messages. Potentially, this could be tuned to be more efficient
147 // with some testing.
148 input_state_
.is_pending
= true;
152 bool ChannelWin::WillDispatchInputMessage(Message
* msg
) {
153 // Make sure we get a hello when client validation is required.
154 if (validate_client_
)
155 return IsHelloMessage(*msg
);
159 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
160 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
161 // The hello message contains one parameter containing the PID.
162 PickleIterator
it(msg
);
164 bool failed
= !it
.ReadInt(&claimed_pid
);
166 if (!failed
&& validate_client_
) {
168 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
174 listener()->OnChannelError();
178 peer_pid_
= claimed_pid
;
179 // Validation completed.
180 validate_client_
= false;
181 listener()->OnChannelConnected(claimed_pid
);
184 bool ChannelWin::DidEmptyInputBuffers() {
185 // We don't need to do anything here.
190 const base::string16
ChannelWin::PipeName(
191 const std::string
& channel_id
, int32
* secret
) {
192 std::string
name("\\\\.\\pipe\\chrome.");
194 // Prevent the shared secret from ending up in the pipe name.
195 size_t index
= channel_id
.find_first_of('\\');
196 if (index
!= std::string::npos
) {
197 if (secret
) // Retrieve the secret if asked for.
198 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
199 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
202 // This case is here to support predictable named pipes in tests.
205 return base::ASCIIToUTF16(name
.append(channel_id
));
208 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
210 DCHECK(!pipe_
.IsValid());
211 base::string16 pipe_name
;
212 // If we already have a valid pipe for channel just copy it.
213 if (channel_handle
.pipe
.handle
) {
214 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
215 // favor of two independent entities (name/file), or it should be a move-
216 // only type with a base::File member. In any case, this code should not
217 // call DuplicateHandle.
218 DCHECK(channel_handle
.name
.empty());
219 pipe_name
= L
"Not Available"; // Just used for LOG
220 // Check that the given pipe confirms to the specified mode. We can
221 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
222 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
224 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
225 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
226 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
227 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
228 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
232 if (!DuplicateHandle(GetCurrentProcess(),
233 channel_handle
.pipe
.handle
,
238 DUPLICATE_SAME_ACCESS
)) {
239 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
242 pipe_
.Set(local_handle
);
243 } else if (mode
& MODE_SERVER_FLAG
) {
244 DCHECK(!channel_handle
.pipe
.handle
);
245 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
246 FILE_FLAG_FIRST_PIPE_INSTANCE
;
247 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
248 validate_client_
= !!client_secret_
;
249 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
251 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
253 Channel::kReadBufferSize
,
254 Channel::kReadBufferSize
,
257 } else if (mode
& MODE_CLIENT_FLAG
) {
258 DCHECK(!channel_handle
.pipe
.handle
);
259 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
260 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
261 GENERIC_READ
| GENERIC_WRITE
,
265 SECURITY_SQOS_PRESENT
| SECURITY_IDENTIFICATION
|
266 FILE_FLAG_OVERLAPPED
,
272 if (!pipe_
.IsValid()) {
273 // If this process is being closed, the pipe may be gone already.
274 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
275 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
279 // Create the Hello message to be sent when Connect is called
280 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
282 IPC::Message::PRIORITY_NORMAL
));
284 // Don't send the secret to the untrusted process, and don't send a secret
285 // if the value is zero (for IPC backwards compatability).
286 int32 secret
= validate_client_
? 0 : client_secret_
;
287 if (!m
->WriteInt(GetCurrentProcessId()) ||
288 (secret
&& !m
->WriteUInt32(secret
))) {
293 output_queue_
.push(m
.release());
297 bool ChannelWin::Connect() {
298 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
300 if (!thread_check_
.get())
301 thread_check_
.reset(new base::ThreadChecker());
303 if (!pipe_
.IsValid())
306 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
308 // Check to see if there is a client connected to our pipe...
309 if (waiting_connect_
)
312 if (!input_state_
.is_pending
) {
313 // Complete setup asynchronously. By not setting input_state_.is_pending
314 // to true, we indicate to OnIOCompleted that this is the special
315 // initialization signal.
316 base::MessageLoopForIO::current()->PostTask(
318 base::Bind(&ChannelWin::OnIOCompleted
,
319 weak_factory_
.GetWeakPtr(),
320 &input_state_
.context
,
325 if (!waiting_connect_
)
326 ProcessOutgoingMessages(NULL
, 0);
330 bool ChannelWin::ProcessConnection() {
331 DCHECK(thread_check_
->CalledOnValidThread());
332 if (input_state_
.is_pending
)
333 input_state_
.is_pending
= false;
335 // Do we have a client connected to our pipe?
336 if (!pipe_
.IsValid())
339 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
340 DWORD err
= GetLastError();
342 // Uhm, the API documentation says that this function should never
343 // return success when used in overlapped mode.
349 case ERROR_IO_PENDING
:
350 input_state_
.is_pending
= true;
352 case ERROR_PIPE_CONNECTED
:
353 waiting_connect_
= false;
356 // The pipe is being closed.
366 bool ChannelWin::ProcessOutgoingMessages(
367 base::MessageLoopForIO::IOContext
* context
,
368 DWORD bytes_written
) {
369 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
371 DCHECK(thread_check_
->CalledOnValidThread());
373 if (output_state_
.is_pending
) {
375 output_state_
.is_pending
= false;
376 if (!context
|| bytes_written
== 0) {
377 DWORD err
= GetLastError();
378 LOG(ERROR
) << "pipe error: " << err
;
382 CHECK(!output_queue_
.empty());
383 Message
* m
= output_queue_
.front();
388 if (output_queue_
.empty())
391 if (!pipe_
.IsValid())
395 Message
* m
= output_queue_
.front();
396 DCHECK(m
->size() <= INT_MAX
);
397 BOOL ok
= WriteFile(pipe_
.Get(),
399 static_cast<uint32
>(m
->size()),
401 &output_state_
.context
.overlapped
);
403 DWORD write_error
= GetLastError();
404 if (write_error
== ERROR_IO_PENDING
) {
405 output_state_
.is_pending
= true;
407 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
408 << " with type " << m
->type();
412 LOG(ERROR
) << "pipe error: " << write_error
;
416 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
417 << " with type " << m
->type();
419 output_state_
.is_pending
= true;
423 void ChannelWin::OnIOCompleted(
424 base::MessageLoopForIO::IOContext
* context
,
425 DWORD bytes_transfered
,
428 DCHECK(thread_check_
->CalledOnValidThread());
429 if (context
== &input_state_
.context
) {
430 if (waiting_connect_
) {
431 if (!ProcessConnection())
433 // We may have some messages queued up to send...
434 if (!output_queue_
.empty() && !output_state_
.is_pending
)
435 ProcessOutgoingMessages(NULL
, 0);
436 if (input_state_
.is_pending
)
438 // else, fall-through and look for incoming messages...
441 // We don't support recursion through OnMessageReceived yet!
442 DCHECK(!processing_incoming_
);
443 base::AutoReset
<bool> auto_reset_processing_incoming(
444 &processing_incoming_
, true);
446 // Process the new data.
447 if (input_state_
.is_pending
) {
448 // This is the normal case for everything except the initialization step.
449 input_state_
.is_pending
= false;
450 if (!bytes_transfered
)
452 else if (pipe_
.IsValid())
453 ok
= AsyncReadComplete(bytes_transfered
);
455 DCHECK(!bytes_transfered
);
458 // Request more data.
460 ok
= ProcessIncomingMessages();
462 DCHECK(context
== &output_state_
.context
);
463 CHECK(output_state_
.is_pending
);
464 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
466 if (!ok
&& pipe_
.IsValid()) {
467 // We don't want to re-enter Close().
469 listener()->OnChannelError();
473 //------------------------------------------------------------------------------
477 scoped_ptr
<Channel
> Channel::Create(
478 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
479 return scoped_ptr
<Channel
>(
480 new ChannelWin(channel_handle
, mode
, listener
));
484 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
485 return ChannelWin::IsNamedServerInitialized(channel_id
);
489 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
490 // Windows pipes can be enumerated by low-privileged processes. So, we
491 // append a strong random value after the \ character. This value is not
492 // included in the pipe name, but sent as part of the client hello, to
493 // hijacking the pipe name to spoof the client.
495 std::string id
= prefix
;
500 do { // Guarantee we get a non-zero value.
501 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
502 } while (secret
== 0);
504 id
.append(GenerateUniqueRandomChannelID());
505 return id
.append(base::StringPrintf("\\%d", secret
));