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/non_thread_safe.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 output_queue_
.push(message
);
92 // ensure waiting to write
93 if (!waiting_connect_
) {
94 if (!output_state_
.is_pending
) {
95 if (!ProcessOutgoingMessages(NULL
, 0))
104 bool Channel::ChannelImpl::IsNamedServerInitialized(
105 const std::string
& channel_id
) {
106 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
108 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
110 return GetLastError() == ERROR_SEM_TIMEOUT
;
113 Channel::ChannelImpl::ReadState
Channel::ChannelImpl::ReadData(
116 int* /* bytes_read */) {
117 if (INVALID_HANDLE_VALUE
== pipe_
)
120 DWORD bytes_read
= 0;
121 BOOL ok
= ReadFile(pipe_
, buffer
, buffer_len
,
122 &bytes_read
, &input_state_
.context
.overlapped
);
124 DWORD err
= GetLastError();
125 if (err
== ERROR_IO_PENDING
) {
126 input_state_
.is_pending
= true;
129 LOG(ERROR
) << "pipe error: " << err
;
133 // We could return READ_SUCCEEDED here. But the way that this code is
134 // structured we instead go back to the message loop. Our completion port
135 // will be signalled even in the "synchronously completed" state.
137 // This allows us to potentially process some outgoing messages and
138 // interleave other work on this thread when we're getting hammered with
139 // input messages. Potentially, this could be tuned to be more efficient
140 // with some testing.
141 input_state_
.is_pending
= true;
145 bool Channel::ChannelImpl::WillDispatchInputMessage(Message
* msg
) {
146 // Make sure we get a hello when client validation is required.
147 if (validate_client_
)
148 return IsHelloMessage(*msg
);
152 void Channel::ChannelImpl::HandleHelloMessage(const Message
& msg
) {
153 // The hello message contains one parameter containing the PID.
154 MessageIterator it
= MessageIterator(msg
);
155 int32 claimed_pid
= it
.NextInt();
156 if (validate_client_
&& (it
.NextInt() != client_secret_
)) {
158 // Something went wrong. Abort connection.
160 listener()->OnChannelError();
163 peer_pid_
= claimed_pid
;
164 // validation completed.
165 validate_client_
= false;
166 listener()->OnChannelConnected(claimed_pid
);
169 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
170 // We don't need to do anything here.
175 const string16
Channel::ChannelImpl::PipeName(
176 const std::string
& channel_id
, int32
* secret
) {
177 std::string
name("\\\\.\\pipe\\chrome.");
179 // Prevent the shared secret from ending up in the pipe name.
180 size_t index
= channel_id
.find_first_of('\\');
181 if (index
!= std::string::npos
) {
182 if (secret
) // Retrieve the secret if asked for.
183 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
184 return ASCIIToWide(name
.append(channel_id
.substr(0, index
- 1)));
187 // This case is here to support predictable named pipes in tests.
190 return ASCIIToWide(name
.append(channel_id
));
193 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
195 DCHECK_EQ(INVALID_HANDLE_VALUE
, pipe_
);
197 // If we already have a valid pipe for channel just copy it.
198 if (channel_handle
.pipe
.handle
) {
199 DCHECK(channel_handle
.name
.empty());
200 pipe_name
= L
"Not Available"; // Just used for LOG
201 // Check that the given pipe confirms to the specified mode. We can
202 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
203 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
205 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
206 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
207 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
208 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
209 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
212 if (!DuplicateHandle(GetCurrentProcess(),
213 channel_handle
.pipe
.handle
,
218 DUPLICATE_SAME_ACCESS
)) {
219 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
222 } else if (mode
& MODE_SERVER_FLAG
) {
223 DCHECK(!channel_handle
.pipe
.handle
);
224 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
225 FILE_FLAG_FIRST_PIPE_INSTANCE
;
226 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
227 validate_client_
= !!client_secret_
;
228 pipe_
= CreateNamedPipeW(pipe_name
.c_str(),
230 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
232 Channel::kReadBufferSize
,
233 Channel::kReadBufferSize
,
236 } else if (mode
& MODE_CLIENT_FLAG
) {
237 DCHECK(!channel_handle
.pipe
.handle
);
238 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
239 pipe_
= CreateFileW(pipe_name
.c_str(),
240 GENERIC_READ
| GENERIC_WRITE
,
244 SECURITY_SQOS_PRESENT
| SECURITY_IDENTIFICATION
|
245 FILE_FLAG_OVERLAPPED
,
251 if (pipe_
== INVALID_HANDLE_VALUE
) {
252 // If this process is being closed, the pipe may be gone already.
253 LOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<<
254 "\" in " << (mode
& MODE_SERVER_FLAG
? "server" : "client")
255 << " mode. Error :" << GetLastError();
259 // Create the Hello message to be sent when Connect is called
260 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
262 IPC::Message::PRIORITY_NORMAL
));
264 // Don't send the secret to the untrusted process, and don't send a secret
265 // if the value is zero (for IPC backwards compatability).
266 int32 secret
= validate_client_
? 0 : client_secret_
;
267 if (!m
->WriteInt(GetCurrentProcessId()) ||
268 (secret
&& !m
->WriteUInt32(secret
))) {
270 pipe_
= INVALID_HANDLE_VALUE
;
274 output_queue_
.push(m
.release());
278 bool Channel::ChannelImpl::Connect() {
279 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
281 if (!thread_check_
.get())
282 thread_check_
.reset(new base::NonThreadSafe());
284 if (pipe_
== INVALID_HANDLE_VALUE
)
287 MessageLoopForIO::current()->RegisterIOHandler(pipe_
, this);
289 // Check to see if there is a client connected to our pipe...
290 if (waiting_connect_
)
293 if (!input_state_
.is_pending
) {
294 // Complete setup asynchronously. By not setting input_state_.is_pending
295 // to true, we indicate to OnIOCompleted that this is the special
296 // initialization signal.
297 MessageLoopForIO::current()->PostTask(
298 FROM_HERE
, base::Bind(&Channel::ChannelImpl::OnIOCompleted
,
299 weak_factory_
.GetWeakPtr(), &input_state_
.context
,
303 if (!waiting_connect_
)
304 ProcessOutgoingMessages(NULL
, 0);
308 bool Channel::ChannelImpl::ProcessConnection() {
309 DCHECK(thread_check_
->CalledOnValidThread());
310 if (input_state_
.is_pending
)
311 input_state_
.is_pending
= false;
313 // Do we have a client connected to our pipe?
314 if (INVALID_HANDLE_VALUE
== pipe_
)
317 BOOL ok
= ConnectNamedPipe(pipe_
, &input_state_
.context
.overlapped
);
319 DWORD err
= GetLastError();
321 // Uhm, the API documentation says that this function should never
322 // return success when used in overlapped mode.
328 case ERROR_IO_PENDING
:
329 input_state_
.is_pending
= true;
331 case ERROR_PIPE_CONNECTED
:
332 waiting_connect_
= false;
335 // The pipe is being closed.
345 bool Channel::ChannelImpl::ProcessOutgoingMessages(
346 MessageLoopForIO::IOContext
* context
,
347 DWORD bytes_written
) {
348 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
350 DCHECK(thread_check_
->CalledOnValidThread());
352 if (output_state_
.is_pending
) {
354 output_state_
.is_pending
= false;
355 if (!context
|| bytes_written
== 0) {
356 DWORD err
= GetLastError();
357 LOG(ERROR
) << "pipe error: " << err
;
361 DCHECK(!output_queue_
.empty());
362 Message
* m
= output_queue_
.front();
367 if (output_queue_
.empty())
370 if (INVALID_HANDLE_VALUE
== pipe_
)
374 Message
* m
= output_queue_
.front();
375 DCHECK(m
->size() <= INT_MAX
);
376 BOOL ok
= WriteFile(pipe_
,
378 static_cast<int>(m
->size()),
380 &output_state_
.context
.overlapped
);
382 DWORD err
= GetLastError();
383 if (err
== ERROR_IO_PENDING
) {
384 output_state_
.is_pending
= true;
386 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
387 << " with type " << m
->type();
391 LOG(ERROR
) << "pipe error: " << err
;
395 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
396 << " with type " << m
->type();
398 output_state_
.is_pending
= true;
402 void Channel::ChannelImpl::OnIOCompleted(MessageLoopForIO::IOContext
* context
,
403 DWORD bytes_transfered
,
406 DCHECK(thread_check_
->CalledOnValidThread());
407 if (context
== &input_state_
.context
) {
408 if (waiting_connect_
) {
409 if (!ProcessConnection())
411 // We may have some messages queued up to send...
412 if (!output_queue_
.empty() && !output_state_
.is_pending
)
413 ProcessOutgoingMessages(NULL
, 0);
414 if (input_state_
.is_pending
)
416 // else, fall-through and look for incoming messages...
419 // We don't support recursion through OnMessageReceived yet!
420 DCHECK(!processing_incoming_
);
421 AutoReset
<bool> auto_reset_processing_incoming(&processing_incoming_
, true);
423 // Process the new data.
424 if (input_state_
.is_pending
) {
425 // This is the normal case for everything except the initialization step.
426 input_state_
.is_pending
= false;
427 if (!bytes_transfered
)
430 ok
= AsyncReadComplete(bytes_transfered
);
432 DCHECK(!bytes_transfered
);
435 // Request more data.
437 ok
= ProcessIncomingMessages();
439 DCHECK(context
== &output_state_
.context
);
440 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
442 if (!ok
&& INVALID_HANDLE_VALUE
!= pipe_
) {
443 // We don't want to re-enter Close().
445 listener()->OnChannelError();
449 //------------------------------------------------------------------------------
450 // Channel's methods simply call through to ChannelImpl.
451 Channel::Channel(const IPC::ChannelHandle
&channel_handle
, Mode mode
,
453 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
456 Channel::~Channel() {
457 delete channel_impl_
;
460 bool Channel::Connect() {
461 return channel_impl_
->Connect();
464 void Channel::Close() {
466 channel_impl_
->Close();
469 void Channel::set_listener(Listener
* listener
) {
470 channel_impl_
->set_listener(listener
);
473 base::ProcessId
Channel::peer_pid() const {
474 return channel_impl_
->peer_pid();
477 bool Channel::Send(Message
* message
) {
478 return channel_impl_
->Send(message
);
482 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
483 return ChannelImpl::IsNamedServerInitialized(channel_id
);
487 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
488 // Windows pipes can be enumerated by low-privileged processes. So, we
489 // append a strong random value after the \ character. This value is not
490 // included in the pipe name, but sent as part of the client hello, to
491 // hijacking the pipe name to spoof the client.
493 std::string id
= prefix
;
498 do { // Guarantee we get a non-zero value.
499 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
500 } while (secret
== 0);
502 id
.append(GenerateUniqueRandomChannelID());
503 return id
.append(base::StringPrintf("\\%d", secret
));