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/process_util.h"
14 #include "base/rand_util.h"
15 #include "base/string_number_conversions.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/utf_string_conversions.h"
18 #include "base/win/scoped_handle.h"
19 #include "ipc/ipc_logging.h"
20 #include "ipc/ipc_message_utils.h"
24 Channel::ChannelImpl::State::State(ChannelImpl
* channel
) : is_pending(false) {
25 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
26 context
.handler
= channel
;
29 Channel::ChannelImpl::State::~State() {
30 COMPILE_ASSERT(!offsetof(Channel::ChannelImpl::State
, context
),
31 starts_with_io_context
);
34 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle
&channel_handle
,
35 Mode mode
, Listener
* listener
)
36 : ChannelReader(listener
),
37 ALLOW_THIS_IN_INITIALIZER_LIST(input_state_(this)),
38 ALLOW_THIS_IN_INITIALIZER_LIST(output_state_(this)),
39 pipe_(INVALID_HANDLE_VALUE
),
40 peer_pid_(base::kNullProcessId
),
41 waiting_connect_(mode
& MODE_SERVER_FLAG
),
42 processing_incoming_(false),
43 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
45 validate_client_(false) {
46 CreatePipe(channel_handle
, mode
);
49 Channel::ChannelImpl::~ChannelImpl() {
53 void Channel::ChannelImpl::Close() {
54 if (thread_check_
.get()) {
55 DCHECK(thread_check_
->CalledOnValidThread());
58 if (input_state_
.is_pending
|| output_state_
.is_pending
)
61 // Closing the handle at this point prevents us from issuing more requests
62 // form OnIOCompleted().
63 if (pipe_
!= INVALID_HANDLE_VALUE
) {
65 pipe_
= INVALID_HANDLE_VALUE
;
68 // Make sure all IO has completed.
69 base::Time start
= base::Time::Now();
70 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
71 MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
74 while (!output_queue_
.empty()) {
75 Message
* m
= output_queue_
.front();
81 bool Channel::ChannelImpl::Send(Message
* message
) {
82 DCHECK(thread_check_
->CalledOnValidThread());
83 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
84 << " with type " << message
->type()
85 << " (" << output_queue_
.size() << " in queue)";
87 #ifdef IPC_MESSAGE_LOG_ENABLED
88 Logging::GetInstance()->OnSendMessage(message
, "");
91 message
->TraceMessageBegin();
92 output_queue_
.push(message
);
93 // ensure waiting to write
94 if (!waiting_connect_
) {
95 if (!output_state_
.is_pending
) {
96 if (!ProcessOutgoingMessages(NULL
, 0))
105 bool Channel::ChannelImpl::IsNamedServerInitialized(
106 const std::string
& channel_id
) {
107 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
109 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
111 return GetLastError() == ERROR_SEM_TIMEOUT
;
114 Channel::ChannelImpl::ReadState
Channel::ChannelImpl::ReadData(
117 int* /* bytes_read */) {
118 if (INVALID_HANDLE_VALUE
== pipe_
)
121 DWORD bytes_read
= 0;
122 BOOL ok
= ReadFile(pipe_
, buffer
, buffer_len
,
123 &bytes_read
, &input_state_
.context
.overlapped
);
125 DWORD err
= GetLastError();
126 if (err
== ERROR_IO_PENDING
) {
127 input_state_
.is_pending
= true;
130 LOG(ERROR
) << "pipe error: " << err
;
134 // We could return READ_SUCCEEDED here. But the way that this code is
135 // structured we instead go back to the message loop. Our completion port
136 // will be signalled even in the "synchronously completed" state.
138 // This allows us to potentially process some outgoing messages and
139 // interleave other work on this thread when we're getting hammered with
140 // input messages. Potentially, this could be tuned to be more efficient
141 // with some testing.
142 input_state_
.is_pending
= true;
146 bool Channel::ChannelImpl::WillDispatchInputMessage(Message
* msg
) {
147 // Make sure we get a hello when client validation is required.
148 if (validate_client_
)
149 return IsHelloMessage(*msg
);
153 void Channel::ChannelImpl::HandleHelloMessage(const Message
& msg
) {
154 // The hello message contains one parameter containing the PID.
155 MessageIterator it
= MessageIterator(msg
);
156 int32 claimed_pid
= it
.NextInt();
157 if (validate_client_
&& (it
.NextInt() != client_secret_
)) {
159 // Something went wrong. Abort connection.
161 listener()->OnChannelError();
164 peer_pid_
= claimed_pid
;
165 // validation completed.
166 validate_client_
= false;
167 listener()->OnChannelConnected(claimed_pid
);
170 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
171 // We don't need to do anything here.
176 const string16
Channel::ChannelImpl::PipeName(
177 const std::string
& channel_id
, int32
* secret
) {
178 std::string
name("\\\\.\\pipe\\chrome.");
180 // Prevent the shared secret from ending up in the pipe name.
181 size_t index
= channel_id
.find_first_of('\\');
182 if (index
!= std::string::npos
) {
183 if (secret
) // Retrieve the secret if asked for.
184 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
185 return ASCIIToWide(name
.append(channel_id
.substr(0, index
- 1)));
188 // This case is here to support predictable named pipes in tests.
191 return ASCIIToWide(name
.append(channel_id
));
194 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
196 DCHECK_EQ(INVALID_HANDLE_VALUE
, pipe_
);
198 // If we already have a valid pipe for channel just copy it.
199 if (channel_handle
.pipe
.handle
) {
200 DCHECK(channel_handle
.name
.empty());
201 pipe_name
= L
"Not Available"; // Just used for LOG
202 // Check that the given pipe confirms to the specified mode. We can
203 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
204 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
206 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
207 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
208 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
209 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
210 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
213 if (!DuplicateHandle(GetCurrentProcess(),
214 channel_handle
.pipe
.handle
,
219 DUPLICATE_SAME_ACCESS
)) {
220 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
223 } else if (mode
& MODE_SERVER_FLAG
) {
224 DCHECK(!channel_handle
.pipe
.handle
);
225 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
226 FILE_FLAG_FIRST_PIPE_INSTANCE
;
227 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
228 validate_client_
= !!client_secret_
;
229 pipe_
= CreateNamedPipeW(pipe_name
.c_str(),
231 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
233 Channel::kReadBufferSize
,
234 Channel::kReadBufferSize
,
237 } else if (mode
& MODE_CLIENT_FLAG
) {
238 DCHECK(!channel_handle
.pipe
.handle
);
239 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
240 pipe_
= CreateFileW(pipe_name
.c_str(),
241 GENERIC_READ
| GENERIC_WRITE
,
245 SECURITY_SQOS_PRESENT
| SECURITY_IDENTIFICATION
|
246 FILE_FLAG_OVERLAPPED
,
252 if (pipe_
== INVALID_HANDLE_VALUE
) {
253 // If this process is being closed, the pipe may be gone already.
254 LOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<<
255 "\" in " << (mode
& MODE_SERVER_FLAG
? "server" : "client")
256 << " mode. Error :" << GetLastError();
260 // Create the Hello message to be sent when Connect is called
261 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
263 IPC::Message::PRIORITY_NORMAL
));
265 // Don't send the secret to the untrusted process, and don't send a secret
266 // if the value is zero (for IPC backwards compatability).
267 int32 secret
= validate_client_
? 0 : client_secret_
;
268 if (!m
->WriteInt(GetCurrentProcessId()) ||
269 (secret
&& !m
->WriteUInt32(secret
))) {
271 pipe_
= INVALID_HANDLE_VALUE
;
275 output_queue_
.push(m
.release());
279 bool Channel::ChannelImpl::Connect() {
280 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
282 if (!thread_check_
.get())
283 thread_check_
.reset(new base::ThreadChecker());
285 if (pipe_
== INVALID_HANDLE_VALUE
)
288 MessageLoopForIO::current()->RegisterIOHandler(pipe_
, this);
290 // Check to see if there is a client connected to our pipe...
291 if (waiting_connect_
)
294 if (!input_state_
.is_pending
) {
295 // Complete setup asynchronously. By not setting input_state_.is_pending
296 // to true, we indicate to OnIOCompleted that this is the special
297 // initialization signal.
298 MessageLoopForIO::current()->PostTask(
299 FROM_HERE
, base::Bind(&Channel::ChannelImpl::OnIOCompleted
,
300 weak_factory_
.GetWeakPtr(), &input_state_
.context
,
304 if (!waiting_connect_
)
305 ProcessOutgoingMessages(NULL
, 0);
309 bool Channel::ChannelImpl::ProcessConnection() {
310 DCHECK(thread_check_
->CalledOnValidThread());
311 if (input_state_
.is_pending
)
312 input_state_
.is_pending
= false;
314 // Do we have a client connected to our pipe?
315 if (INVALID_HANDLE_VALUE
== pipe_
)
318 BOOL ok
= ConnectNamedPipe(pipe_
, &input_state_
.context
.overlapped
);
320 DWORD err
= GetLastError();
322 // Uhm, the API documentation says that this function should never
323 // return success when used in overlapped mode.
329 case ERROR_IO_PENDING
:
330 input_state_
.is_pending
= true;
332 case ERROR_PIPE_CONNECTED
:
333 waiting_connect_
= false;
336 // The pipe is being closed.
346 bool Channel::ChannelImpl::ProcessOutgoingMessages(
347 MessageLoopForIO::IOContext
* context
,
348 DWORD bytes_written
) {
349 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
351 DCHECK(thread_check_
->CalledOnValidThread());
353 if (output_state_
.is_pending
) {
355 output_state_
.is_pending
= false;
356 if (!context
|| bytes_written
== 0) {
357 DWORD err
= GetLastError();
358 LOG(ERROR
) << "pipe error: " << err
;
362 DCHECK(!output_queue_
.empty());
363 Message
* m
= output_queue_
.front();
368 if (output_queue_
.empty())
371 if (INVALID_HANDLE_VALUE
== pipe_
)
375 Message
* m
= output_queue_
.front();
376 DCHECK(m
->size() <= INT_MAX
);
377 BOOL ok
= WriteFile(pipe_
,
379 static_cast<int>(m
->size()),
381 &output_state_
.context
.overlapped
);
383 DWORD err
= GetLastError();
384 if (err
== ERROR_IO_PENDING
) {
385 output_state_
.is_pending
= true;
387 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
388 << " with type " << m
->type();
392 LOG(ERROR
) << "pipe error: " << err
;
396 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
397 << " with type " << m
->type();
399 output_state_
.is_pending
= true;
403 void Channel::ChannelImpl::OnIOCompleted(MessageLoopForIO::IOContext
* context
,
404 DWORD bytes_transfered
,
407 DCHECK(thread_check_
->CalledOnValidThread());
408 if (context
== &input_state_
.context
) {
409 if (waiting_connect_
) {
410 if (!ProcessConnection())
412 // We may have some messages queued up to send...
413 if (!output_queue_
.empty() && !output_state_
.is_pending
)
414 ProcessOutgoingMessages(NULL
, 0);
415 if (input_state_
.is_pending
)
417 // else, fall-through and look for incoming messages...
420 // We don't support recursion through OnMessageReceived yet!
421 DCHECK(!processing_incoming_
);
422 AutoReset
<bool> auto_reset_processing_incoming(&processing_incoming_
, true);
424 // Process the new data.
425 if (input_state_
.is_pending
) {
426 // This is the normal case for everything except the initialization step.
427 input_state_
.is_pending
= false;
428 if (!bytes_transfered
)
431 ok
= AsyncReadComplete(bytes_transfered
);
433 DCHECK(!bytes_transfered
);
436 // Request more data.
438 ok
= ProcessIncomingMessages();
440 DCHECK(context
== &output_state_
.context
);
441 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
443 if (!ok
&& INVALID_HANDLE_VALUE
!= pipe_
) {
444 // We don't want to re-enter Close().
446 listener()->OnChannelError();
450 //------------------------------------------------------------------------------
451 // Channel's methods simply call through to ChannelImpl.
452 Channel::Channel(const IPC::ChannelHandle
&channel_handle
, Mode mode
,
454 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
457 Channel::~Channel() {
458 delete channel_impl_
;
461 bool Channel::Connect() {
462 return channel_impl_
->Connect();
465 void Channel::Close() {
467 channel_impl_
->Close();
470 void Channel::set_listener(Listener
* listener
) {
471 channel_impl_
->set_listener(listener
);
474 base::ProcessId
Channel::peer_pid() const {
475 return channel_impl_
->peer_pid();
478 bool Channel::Send(Message
* message
) {
479 return channel_impl_
->Send(message
);
483 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
484 return ChannelImpl::IsNamedServerInitialized(channel_id
);
488 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
489 // Windows pipes can be enumerated by low-privileged processes. So, we
490 // append a strong random value after the \ character. This value is not
491 // included in the pipe name, but sent as part of the client hello, to
492 // hijacking the pipe name to spoof the client.
494 std::string id
= prefix
;
499 do { // Guarantee we get a non-zero value.
500 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
501 } while (secret
== 0);
503 id
.append(GenerateUniqueRandomChannelID());
504 return id
.append(base::StringPrintf("\\%d", secret
));