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 pipe_(INVALID_HANDLE_VALUE
),
42 peer_pid_(base::kNullProcessId
),
43 waiting_connect_(mode
& MODE_SERVER_FLAG
),
44 processing_incoming_(false),
47 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());
60 if (input_state_
.is_pending
|| output_state_
.is_pending
)
63 // Closing the handle at this point prevents us from issuing more requests
64 // form OnIOCompleted().
65 if (pipe_
!= INVALID_HANDLE_VALUE
) {
67 pipe_
= INVALID_HANDLE_VALUE
;
70 // Make sure all IO has completed.
71 base::Time start
= base::Time::Now();
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();
83 bool ChannelWin::Send(Message
* message
) {
84 DCHECK(thread_check_
->CalledOnValidThread());
85 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
86 << " with type " << message
->type()
87 << " (" << output_queue_
.size() << " in queue)";
89 #ifdef IPC_MESSAGE_LOG_ENABLED
90 Logging::GetInstance()->OnSendMessage(message
, "");
93 message
->TraceMessageBegin();
94 output_queue_
.push(message
);
95 // ensure waiting to write
96 if (!waiting_connect_
) {
97 if (!output_state_
.is_pending
) {
98 if (!ProcessOutgoingMessages(NULL
, 0))
106 base::ProcessId
ChannelWin::GetPeerPID() const {
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 (INVALID_HANDLE_VALUE
== pipe_
)
127 DWORD bytes_read
= 0;
128 BOOL ok
= ReadFile(pipe_
, 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::ASCIIToWide(name
.append(channel_id
.substr(0, index
- 1)));
202 // This case is here to support predictable named pipes in tests.
205 return base::ASCIIToWide(name
.append(channel_id
));
208 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
210 DCHECK_EQ(INVALID_HANDLE_VALUE
, pipe_
);
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 DCHECK(channel_handle
.name
.empty());
215 pipe_name
= L
"Not Available"; // Just used for LOG
216 // Check that the given pipe confirms to the specified mode. We can
217 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
218 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
220 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
221 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
222 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
223 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
224 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
227 if (!DuplicateHandle(GetCurrentProcess(),
228 channel_handle
.pipe
.handle
,
233 DUPLICATE_SAME_ACCESS
)) {
234 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
237 } else if (mode
& MODE_SERVER_FLAG
) {
238 DCHECK(!channel_handle
.pipe
.handle
);
239 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
240 FILE_FLAG_FIRST_PIPE_INSTANCE
;
241 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
242 validate_client_
= !!client_secret_
;
243 pipe_
= CreateNamedPipeW(pipe_name
.c_str(),
245 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
247 Channel::kReadBufferSize
,
248 Channel::kReadBufferSize
,
251 } else if (mode
& MODE_CLIENT_FLAG
) {
252 DCHECK(!channel_handle
.pipe
.handle
);
253 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
254 pipe_
= CreateFileW(pipe_name
.c_str(),
255 GENERIC_READ
| GENERIC_WRITE
,
259 SECURITY_SQOS_PRESENT
| SECURITY_IDENTIFICATION
|
260 FILE_FLAG_OVERLAPPED
,
266 if (pipe_
== INVALID_HANDLE_VALUE
) {
267 // If this process is being closed, the pipe may be gone already.
268 LOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<<
269 "\" in " << (mode
& MODE_SERVER_FLAG
? "server" : "client")
270 << " mode. Error :" << GetLastError();
274 // Create the Hello message to be sent when Connect is called
275 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
277 IPC::Message::PRIORITY_NORMAL
));
279 // Don't send the secret to the untrusted process, and don't send a secret
280 // if the value is zero (for IPC backwards compatability).
281 int32 secret
= validate_client_
? 0 : client_secret_
;
282 if (!m
->WriteInt(GetCurrentProcessId()) ||
283 (secret
&& !m
->WriteUInt32(secret
))) {
285 pipe_
= INVALID_HANDLE_VALUE
;
289 output_queue_
.push(m
.release());
293 bool ChannelWin::Connect() {
294 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
296 if (!thread_check_
.get())
297 thread_check_
.reset(new base::ThreadChecker());
299 if (pipe_
== INVALID_HANDLE_VALUE
)
302 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
, this);
304 // Check to see if there is a client connected to our pipe...
305 if (waiting_connect_
)
308 if (!input_state_
.is_pending
) {
309 // Complete setup asynchronously. By not setting input_state_.is_pending
310 // to true, we indicate to OnIOCompleted that this is the special
311 // initialization signal.
312 base::MessageLoopForIO::current()->PostTask(
314 base::Bind(&ChannelWin::OnIOCompleted
,
315 weak_factory_
.GetWeakPtr(),
316 &input_state_
.context
,
321 if (!waiting_connect_
)
322 ProcessOutgoingMessages(NULL
, 0);
326 bool ChannelWin::ProcessConnection() {
327 DCHECK(thread_check_
->CalledOnValidThread());
328 if (input_state_
.is_pending
)
329 input_state_
.is_pending
= false;
331 // Do we have a client connected to our pipe?
332 if (INVALID_HANDLE_VALUE
== pipe_
)
335 BOOL ok
= ConnectNamedPipe(pipe_
, &input_state_
.context
.overlapped
);
337 DWORD err
= GetLastError();
339 // Uhm, the API documentation says that this function should never
340 // return success when used in overlapped mode.
346 case ERROR_IO_PENDING
:
347 input_state_
.is_pending
= true;
349 case ERROR_PIPE_CONNECTED
:
350 waiting_connect_
= false;
353 // The pipe is being closed.
363 bool ChannelWin::ProcessOutgoingMessages(
364 base::MessageLoopForIO::IOContext
* context
,
365 DWORD bytes_written
) {
366 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
368 DCHECK(thread_check_
->CalledOnValidThread());
370 if (output_state_
.is_pending
) {
372 output_state_
.is_pending
= false;
373 if (!context
|| bytes_written
== 0) {
374 DWORD err
= GetLastError();
375 LOG(ERROR
) << "pipe error: " << err
;
379 CHECK(!output_queue_
.empty());
380 Message
* m
= output_queue_
.front();
385 if (output_queue_
.empty())
388 if (INVALID_HANDLE_VALUE
== pipe_
)
392 Message
* m
= output_queue_
.front();
393 DCHECK(m
->size() <= INT_MAX
);
394 BOOL ok
= WriteFile(pipe_
,
396 static_cast<int>(m
->size()),
398 &output_state_
.context
.overlapped
);
400 DWORD err
= GetLastError();
401 if (err
== ERROR_IO_PENDING
) {
402 output_state_
.is_pending
= true;
404 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
405 << " with type " << m
->type();
409 LOG(ERROR
) << "pipe error: " << err
;
413 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
414 << " with type " << m
->type();
416 output_state_
.is_pending
= true;
420 void ChannelWin::OnIOCompleted(
421 base::MessageLoopForIO::IOContext
* context
,
422 DWORD bytes_transfered
,
425 DCHECK(thread_check_
->CalledOnValidThread());
426 if (context
== &input_state_
.context
) {
427 if (waiting_connect_
) {
428 if (!ProcessConnection())
430 // We may have some messages queued up to send...
431 if (!output_queue_
.empty() && !output_state_
.is_pending
)
432 ProcessOutgoingMessages(NULL
, 0);
433 if (input_state_
.is_pending
)
435 // else, fall-through and look for incoming messages...
438 // We don't support recursion through OnMessageReceived yet!
439 DCHECK(!processing_incoming_
);
440 base::AutoReset
<bool> auto_reset_processing_incoming(
441 &processing_incoming_
, true);
443 // Process the new data.
444 if (input_state_
.is_pending
) {
445 // This is the normal case for everything except the initialization step.
446 input_state_
.is_pending
= false;
447 if (!bytes_transfered
)
449 else if (pipe_
!= INVALID_HANDLE_VALUE
)
450 ok
= AsyncReadComplete(bytes_transfered
);
452 DCHECK(!bytes_transfered
);
455 // Request more data.
457 ok
= ProcessIncomingMessages();
459 DCHECK(context
== &output_state_
.context
);
460 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
462 if (!ok
&& INVALID_HANDLE_VALUE
!= pipe_
) {
463 // We don't want to re-enter Close().
465 listener()->OnChannelError();
469 //------------------------------------------------------------------------------
473 scoped_ptr
<Channel
> Channel::Create(
474 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
475 return scoped_ptr
<Channel
>(
476 new ChannelWin(channel_handle
, mode
, listener
));
480 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
481 return ChannelWin::IsNamedServerInitialized(channel_id
);
485 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
486 // Windows pipes can be enumerated by low-privileged processes. So, we
487 // append a strong random value after the \ character. This value is not
488 // included in the pipe name, but sent as part of the client hello, to
489 // hijacking the pipe name to spoof the client.
491 std::string id
= prefix
;
496 do { // Guarantee we get a non-zero value.
497 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
498 } while (secret
== 0);
500 id
.append(GenerateUniqueRandomChannelID());
501 return id
.append(base::StringPrintf("\\%d", secret
));