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"
28 CALLED_CONNECT
= 1 << 1,
29 PENDING_CONNECT
= 1 << 2,
30 CONNECT_COMPLETED
= 1 << 3,
31 PIPE_CONNECTED
= 1 << 4,
34 WRITE_COMPLETED
= 1 << 7,
35 READ_COMPLETED
= 1 << 8,
37 WAIT_FOR_READ
= 1 << 10,
38 WAIT_FOR_WRITE
= 1 << 11,
39 WAIT_FOR_READ_COMPLETE
= 1 << 12,
40 WAIT_FOR_WRITE_COMPLETE
= 1 << 13
47 ChannelWin::State::State(ChannelWin
* channel
) : is_pending(false) {
48 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
49 context
.handler
= channel
;
52 ChannelWin::State::~State() {
53 COMPILE_ASSERT(!offsetof(ChannelWin::State
, context
),
54 starts_with_io_context
);
57 ChannelWin::ChannelWin(const IPC::ChannelHandle
&channel_handle
,
58 Mode mode
, Listener
* listener
)
59 : ChannelReader(listener
),
62 pipe_(INVALID_HANDLE_VALUE
),
63 peer_pid_(base::kNullProcessId
),
64 waiting_connect_(mode
& MODE_SERVER_FLAG
),
65 processing_incoming_(false),
67 validate_client_(false),
70 CreatePipe(channel_handle
, mode
);
73 ChannelWin::~ChannelWin() {
77 void ChannelWin::Close() {
78 if (thread_check_
.get()) {
79 DCHECK(thread_check_
->CalledOnValidThread());
81 debug_flags_
|= CLOSED
;
83 if (input_state_
.is_pending
|| output_state_
.is_pending
)
86 // Closing the handle at this point prevents us from issuing more requests
87 // form OnIOCompleted().
88 if (pipe_
!= INVALID_HANDLE_VALUE
) {
90 pipe_
= INVALID_HANDLE_VALUE
;
93 if (input_state_
.is_pending
)
94 debug_flags_
|= WAIT_FOR_READ
;
96 if (output_state_
.is_pending
)
97 debug_flags_
|= WAIT_FOR_WRITE
;
99 // Make sure all IO has completed.
100 base::Time start
= base::Time::Now();
101 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
102 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
105 while (!output_queue_
.empty()) {
106 Message
* m
= output_queue_
.front();
112 bool ChannelWin::Send(Message
* message
) {
113 DCHECK(thread_check_
->CalledOnValidThread());
114 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
115 << " with type " << message
->type()
116 << " (" << output_queue_
.size() << " in queue)";
118 #ifdef IPC_MESSAGE_LOG_ENABLED
119 Logging::GetInstance()->OnSendMessage(message
, "");
122 message
->TraceMessageBegin();
123 output_queue_
.push(message
);
124 // ensure waiting to write
125 if (!waiting_connect_
) {
126 if (!output_state_
.is_pending
) {
127 if (!ProcessOutgoingMessages(NULL
, 0))
135 base::ProcessId
ChannelWin::GetPeerPID() const {
140 bool ChannelWin::IsNamedServerInitialized(
141 const std::string
& channel_id
) {
142 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
144 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
146 return GetLastError() == ERROR_SEM_TIMEOUT
;
149 ChannelWin::ReadState
ChannelWin::ReadData(
152 int* /* bytes_read */) {
153 if (INVALID_HANDLE_VALUE
== pipe_
)
156 debug_flags_
|= READ_MSG
;
157 DWORD bytes_read
= 0;
158 BOOL ok
= ReadFile(pipe_
, buffer
, buffer_len
,
159 &bytes_read
, &input_state_
.context
.overlapped
);
161 DWORD err
= GetLastError();
162 if (err
== ERROR_IO_PENDING
) {
163 input_state_
.is_pending
= true;
166 LOG(ERROR
) << "pipe error: " << err
;
170 // We could return READ_SUCCEEDED here. But the way that this code is
171 // structured we instead go back to the message loop. Our completion port
172 // will be signalled even in the "synchronously completed" state.
174 // This allows us to potentially process some outgoing messages and
175 // interleave other work on this thread when we're getting hammered with
176 // input messages. Potentially, this could be tuned to be more efficient
177 // with some testing.
178 input_state_
.is_pending
= true;
182 bool ChannelWin::WillDispatchInputMessage(Message
* msg
) {
183 // Make sure we get a hello when client validation is required.
184 if (validate_client_
)
185 return IsHelloMessage(*msg
);
189 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
190 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
191 // The hello message contains one parameter containing the PID.
192 PickleIterator
it(msg
);
194 bool failed
= !it
.ReadInt(&claimed_pid
);
196 if (!failed
&& validate_client_
) {
198 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
204 listener()->OnChannelError();
208 peer_pid_
= claimed_pid
;
209 // Validation completed.
210 validate_client_
= false;
211 listener()->OnChannelConnected(claimed_pid
);
214 bool ChannelWin::DidEmptyInputBuffers() {
215 // We don't need to do anything here.
220 const base::string16
ChannelWin::PipeName(
221 const std::string
& channel_id
, int32
* secret
) {
222 std::string
name("\\\\.\\pipe\\chrome.");
224 // Prevent the shared secret from ending up in the pipe name.
225 size_t index
= channel_id
.find_first_of('\\');
226 if (index
!= std::string::npos
) {
227 if (secret
) // Retrieve the secret if asked for.
228 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
229 return base::ASCIIToWide(name
.append(channel_id
.substr(0, index
- 1)));
232 // This case is here to support predictable named pipes in tests.
235 return base::ASCIIToWide(name
.append(channel_id
));
238 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
240 DCHECK_EQ(INVALID_HANDLE_VALUE
, pipe_
);
241 base::string16 pipe_name
;
242 // If we already have a valid pipe for channel just copy it.
243 if (channel_handle
.pipe
.handle
) {
244 DCHECK(channel_handle
.name
.empty());
245 pipe_name
= L
"Not Available"; // Just used for LOG
246 // Check that the given pipe confirms to the specified mode. We can
247 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
248 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
250 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
251 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
252 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
253 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
254 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
257 if (!DuplicateHandle(GetCurrentProcess(),
258 channel_handle
.pipe
.handle
,
263 DUPLICATE_SAME_ACCESS
)) {
264 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
267 } else if (mode
& MODE_SERVER_FLAG
) {
268 DCHECK(!channel_handle
.pipe
.handle
);
269 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
270 FILE_FLAG_FIRST_PIPE_INSTANCE
;
271 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
272 validate_client_
= !!client_secret_
;
273 pipe_
= CreateNamedPipeW(pipe_name
.c_str(),
275 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
277 Channel::kReadBufferSize
,
278 Channel::kReadBufferSize
,
281 } else if (mode
& MODE_CLIENT_FLAG
) {
282 DCHECK(!channel_handle
.pipe
.handle
);
283 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
284 pipe_
= CreateFileW(pipe_name
.c_str(),
285 GENERIC_READ
| GENERIC_WRITE
,
289 SECURITY_SQOS_PRESENT
| SECURITY_IDENTIFICATION
|
290 FILE_FLAG_OVERLAPPED
,
296 if (pipe_
== INVALID_HANDLE_VALUE
) {
297 // If this process is being closed, the pipe may be gone already.
298 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
299 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
303 // Create the Hello message to be sent when Connect is called
304 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
306 IPC::Message::PRIORITY_NORMAL
));
308 // Don't send the secret to the untrusted process, and don't send a secret
309 // if the value is zero (for IPC backwards compatability).
310 int32 secret
= validate_client_
? 0 : client_secret_
;
311 if (!m
->WriteInt(GetCurrentProcessId()) ||
312 (secret
&& !m
->WriteUInt32(secret
))) {
314 pipe_
= INVALID_HANDLE_VALUE
;
318 debug_flags_
|= INIT_DONE
;
320 output_queue_
.push(m
.release());
324 bool ChannelWin::Connect() {
325 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
327 if (!thread_check_
.get())
328 thread_check_
.reset(new base::ThreadChecker());
330 if (pipe_
== INVALID_HANDLE_VALUE
)
333 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
, this);
335 // Check to see if there is a client connected to our pipe...
336 if (waiting_connect_
)
339 if (!input_state_
.is_pending
) {
340 // Complete setup asynchronously. By not setting input_state_.is_pending
341 // to true, we indicate to OnIOCompleted that this is the special
342 // initialization signal.
343 base::MessageLoopForIO::current()->PostTask(
345 base::Bind(&ChannelWin::OnIOCompleted
,
346 weak_factory_
.GetWeakPtr(),
347 &input_state_
.context
,
352 if (!waiting_connect_
)
353 ProcessOutgoingMessages(NULL
, 0);
357 bool ChannelWin::ProcessConnection() {
358 DCHECK(thread_check_
->CalledOnValidThread());
359 if (input_state_
.is_pending
)
360 input_state_
.is_pending
= false;
362 // Do we have a client connected to our pipe?
363 if (INVALID_HANDLE_VALUE
== pipe_
)
366 BOOL ok
= ConnectNamedPipe(pipe_
, &input_state_
.context
.overlapped
);
367 debug_flags_
|= CALLED_CONNECT
;
369 DWORD err
= GetLastError();
371 // Uhm, the API documentation says that this function should never
372 // return success when used in overlapped mode.
378 case ERROR_IO_PENDING
:
379 input_state_
.is_pending
= true;
380 debug_flags_
|= PENDING_CONNECT
;
382 case ERROR_PIPE_CONNECTED
:
383 debug_flags_
|= PIPE_CONNECTED
;
384 waiting_connect_
= false;
387 // The pipe is being closed.
397 bool ChannelWin::ProcessOutgoingMessages(
398 base::MessageLoopForIO::IOContext
* context
,
399 DWORD bytes_written
) {
400 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
402 DCHECK(thread_check_
->CalledOnValidThread());
404 if (output_state_
.is_pending
) {
406 output_state_
.is_pending
= false;
407 if (!context
|| bytes_written
== 0) {
408 DWORD err
= GetLastError();
409 LOG(ERROR
) << "pipe error: " << err
;
413 CHECK(!output_queue_
.empty());
414 Message
* m
= output_queue_
.front();
419 if (output_queue_
.empty())
422 if (INVALID_HANDLE_VALUE
== pipe_
)
426 Message
* m
= output_queue_
.front();
427 DCHECK(m
->size() <= INT_MAX
);
428 debug_flags_
|= WRITE_MSG
;
429 BOOL ok
= WriteFile(pipe_
,
431 static_cast<int>(m
->size()),
433 &output_state_
.context
.overlapped
);
435 DWORD err
= GetLastError();
436 if (err
== ERROR_IO_PENDING
) {
437 output_state_
.is_pending
= true;
439 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
440 << " with type " << m
->type();
444 LOG(ERROR
) << "pipe error: " << err
;
448 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
449 << " with type " << m
->type();
451 output_state_
.is_pending
= true;
455 void ChannelWin::OnIOCompleted(
456 base::MessageLoopForIO::IOContext
* context
,
457 DWORD bytes_transfered
,
460 DCHECK(thread_check_
->CalledOnValidThread());
461 if (context
== &input_state_
.context
) {
462 if (waiting_connect_
) {
463 debug_flags_
|= CONNECT_COMPLETED
;
464 if (!ProcessConnection())
466 // We may have some messages queued up to send...
467 if (!output_queue_
.empty() && !output_state_
.is_pending
)
468 ProcessOutgoingMessages(NULL
, 0);
469 if (input_state_
.is_pending
)
471 // else, fall-through and look for incoming messages...
474 // We don't support recursion through OnMessageReceived yet!
475 DCHECK(!processing_incoming_
);
476 base::AutoReset
<bool> auto_reset_processing_incoming(
477 &processing_incoming_
, true);
479 // Process the new data.
480 if (input_state_
.is_pending
) {
481 // This is the normal case for everything except the initialization step.
482 debug_flags_
|= READ_COMPLETED
;
483 if (debug_flags_
& WAIT_FOR_READ
) {
484 CHECK(!(debug_flags_
& WAIT_FOR_READ_COMPLETE
));
485 debug_flags_
|= WAIT_FOR_READ_COMPLETE
;
487 input_state_
.is_pending
= false;
488 if (!bytes_transfered
)
490 else if (pipe_
!= INVALID_HANDLE_VALUE
)
491 ok
= AsyncReadComplete(bytes_transfered
);
493 DCHECK(!bytes_transfered
);
496 // Request more data.
498 ok
= ProcessIncomingMessages();
500 DCHECK(context
== &output_state_
.context
);
501 debug_flags_
|= WRITE_COMPLETED
;
502 if (debug_flags_
& WAIT_FOR_WRITE
) {
503 CHECK(!(debug_flags_
& WAIT_FOR_WRITE_COMPLETE
));
504 debug_flags_
|= WAIT_FOR_WRITE_COMPLETE
;
506 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
508 if (!ok
&& INVALID_HANDLE_VALUE
!= pipe_
) {
509 // We don't want to re-enter Close().
511 listener()->OnChannelError();
515 //------------------------------------------------------------------------------
519 scoped_ptr
<Channel
> Channel::Create(
520 const IPC::ChannelHandle
&channel_handle
, Mode mode
, Listener
* listener
) {
521 return scoped_ptr
<Channel
>(
522 new ChannelWin(channel_handle
, mode
, listener
));
526 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
527 return ChannelWin::IsNamedServerInitialized(channel_id
);
531 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
532 // Windows pipes can be enumerated by low-privileged processes. So, we
533 // append a strong random value after the \ character. This value is not
534 // included in the pipe name, but sent as part of the client hello, to
535 // hijacking the pipe name to spoof the client.
537 std::string id
= prefix
;
542 do { // Guarantee we get a non-zero value.
543 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
544 } while (secret
== 0);
546 id
.append(GenerateUniqueRandomChannelID());
547 return id
.append(base::StringPrintf("\\%d", secret
));