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_attachment_set.h"
23 #include "ipc/ipc_message_utils.h"
27 ChannelWin::State::State(ChannelWin
* channel
) : is_pending(false) {
28 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
29 context
.handler
= channel
;
32 ChannelWin::State::~State() {
33 static_assert(offsetof(ChannelWin::State
, context
) == 0,
34 "ChannelWin::State should have context as its first data"
38 ChannelWin::ChannelWin(const IPC::ChannelHandle
& channel_handle
,
41 AttachmentBroker
* broker
)
42 : ChannelReader(listener
),
45 peer_pid_(base::kNullProcessId
),
46 waiting_connect_(mode
& MODE_SERVER_FLAG
),
47 processing_incoming_(false),
48 validate_client_(false),
52 CreatePipe(channel_handle
, mode
);
55 ChannelWin::~ChannelWin() {
59 void ChannelWin::Close() {
60 if (thread_check_
.get())
61 DCHECK(thread_check_
->CalledOnValidThread());
63 if (input_state_
.is_pending
|| output_state_
.is_pending
)
64 CancelIo(pipe_
.Get());
66 // Closing the handle at this point prevents us from issuing more requests
67 // form OnIOCompleted().
71 // Make sure all IO has completed.
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 // TODO(erikchen): Remove this DCHECK once ChannelWin fully supports
85 // brokerable attachments. http://crbug.com/493414.
86 DCHECK(!message
->HasAttachments());
87 DCHECK(thread_check_
->CalledOnValidThread());
88 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
89 << " with type " << message
->type()
90 << " (" << output_queue_
.size() << " in queue)";
92 // Sending a brokerable attachment requires a call to Channel::Send(), so
93 // Send() may be re-entrant. Brokered attachments must be sent before the
95 if (message
->HasBrokerableAttachments()) {
97 for (const BrokerableAttachment
* attachment
:
98 message
->attachment_set()->PeekBrokerableAttachments()) {
99 if (!broker_
->SendAttachmentToProcess(attachment
, peer_pid_
))
104 #ifdef IPC_MESSAGE_LOG_ENABLED
105 Logging::GetInstance()->OnSendMessage(message
, "");
108 message
->TraceMessageBegin();
109 output_queue_
.push(message
);
110 // ensure waiting to write
111 if (!waiting_connect_
) {
112 if (!output_state_
.is_pending
) {
113 if (!ProcessOutgoingMessages(NULL
, 0))
121 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
125 base::ProcessId
ChannelWin::GetPeerPID() const {
129 base::ProcessId
ChannelWin::GetSelfPID() const {
130 return GetCurrentProcessId();
134 bool ChannelWin::IsNamedServerInitialized(
135 const std::string
& channel_id
) {
136 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
138 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
140 return GetLastError() == ERROR_SEM_TIMEOUT
;
143 ChannelWin::ReadState
ChannelWin::ReadData(
146 int* /* bytes_read */) {
147 if (!pipe_
.IsValid())
150 DWORD bytes_read
= 0;
151 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
152 &bytes_read
, &input_state_
.context
.overlapped
);
154 DWORD err
= GetLastError();
155 if (err
== ERROR_IO_PENDING
) {
156 input_state_
.is_pending
= true;
159 LOG(ERROR
) << "pipe error: " << err
;
163 // We could return READ_SUCCEEDED here. But the way that this code is
164 // structured we instead go back to the message loop. Our completion port
165 // will be signalled even in the "synchronously completed" state.
167 // This allows us to potentially process some outgoing messages and
168 // interleave other work on this thread when we're getting hammered with
169 // input messages. Potentially, this could be tuned to be more efficient
170 // with some testing.
171 input_state_
.is_pending
= true;
175 bool ChannelWin::WillDispatchInputMessage(Message
* msg
) {
176 // Make sure we get a hello when client validation is required.
177 if (validate_client_
)
178 return IsHelloMessage(*msg
);
182 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
183 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
184 // The hello message contains one parameter containing the PID.
185 base::PickleIterator
it(msg
);
187 bool failed
= !it
.ReadInt(&claimed_pid
);
189 if (!failed
&& validate_client_
) {
191 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
197 listener()->OnChannelError();
201 peer_pid_
= claimed_pid
;
202 // Validation completed.
203 validate_client_
= false;
204 listener()->OnChannelConnected(claimed_pid
);
207 bool ChannelWin::DidEmptyInputBuffers() {
208 // We don't need to do anything here.
213 const base::string16
ChannelWin::PipeName(
214 const std::string
& channel_id
, int32
* secret
) {
215 std::string
name("\\\\.\\pipe\\chrome.");
217 // Prevent the shared secret from ending up in the pipe name.
218 size_t index
= channel_id
.find_first_of('\\');
219 if (index
!= std::string::npos
) {
220 if (secret
) // Retrieve the secret if asked for.
221 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
222 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
225 // This case is here to support predictable named pipes in tests.
228 return base::ASCIIToUTF16(name
.append(channel_id
));
231 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
233 DCHECK(!pipe_
.IsValid());
234 base::string16 pipe_name
;
235 // If we already have a valid pipe for channel just copy it.
236 if (channel_handle
.pipe
.handle
) {
237 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
238 // favor of two independent entities (name/file), or it should be a move-
239 // only type with a base::File member. In any case, this code should not
240 // call DuplicateHandle.
241 DCHECK(channel_handle
.name
.empty());
242 pipe_name
= L
"Not Available"; // Just used for LOG
243 // Check that the given pipe confirms to the specified mode. We can
244 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
245 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
247 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
248 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
249 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
250 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
251 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
255 if (!DuplicateHandle(GetCurrentProcess(),
256 channel_handle
.pipe
.handle
,
261 DUPLICATE_SAME_ACCESS
)) {
262 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
265 pipe_
.Set(local_handle
);
266 } else if (mode
& MODE_SERVER_FLAG
) {
267 DCHECK(!channel_handle
.pipe
.handle
);
268 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
269 FILE_FLAG_FIRST_PIPE_INSTANCE
;
270 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
271 validate_client_
= !!client_secret_
;
272 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
274 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
276 Channel::kReadBufferSize
,
277 Channel::kReadBufferSize
,
280 } else if (mode
& MODE_CLIENT_FLAG
) {
281 DCHECK(!channel_handle
.pipe
.handle
);
282 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
283 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
284 GENERIC_READ
| GENERIC_WRITE
,
288 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
289 FILE_FLAG_OVERLAPPED
,
295 if (!pipe_
.IsValid()) {
296 // If this process is being closed, the pipe may be gone already.
297 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
298 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
302 // Create the Hello message to be sent when Connect is called
303 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
305 IPC::Message::PRIORITY_NORMAL
));
307 // Don't send the secret to the untrusted process, and don't send a secret
308 // if the value is zero (for IPC backwards compatability).
309 int32 secret
= validate_client_
? 0 : client_secret_
;
310 if (!m
->WriteInt(GetCurrentProcessId()) ||
311 (secret
&& !m
->WriteUInt32(secret
))) {
316 output_queue_
.push(m
.release());
320 bool ChannelWin::Connect() {
321 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
323 if (!thread_check_
.get())
324 thread_check_
.reset(new base::ThreadChecker());
326 if (!pipe_
.IsValid())
329 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
331 // Check to see if there is a client connected to our pipe...
332 if (waiting_connect_
)
335 if (!input_state_
.is_pending
) {
336 // Complete setup asynchronously. By not setting input_state_.is_pending
337 // to true, we indicate to OnIOCompleted that this is the special
338 // initialization signal.
339 base::MessageLoopForIO::current()->PostTask(
341 base::Bind(&ChannelWin::OnIOCompleted
,
342 weak_factory_
.GetWeakPtr(),
343 &input_state_
.context
,
348 if (!waiting_connect_
)
349 ProcessOutgoingMessages(NULL
, 0);
353 bool ChannelWin::ProcessConnection() {
354 DCHECK(thread_check_
->CalledOnValidThread());
355 if (input_state_
.is_pending
)
356 input_state_
.is_pending
= false;
358 // Do we have a client connected to our pipe?
359 if (!pipe_
.IsValid())
362 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
363 DWORD err
= GetLastError();
365 // Uhm, the API documentation says that this function should never
366 // return success when used in overlapped mode.
372 case ERROR_IO_PENDING
:
373 input_state_
.is_pending
= true;
375 case ERROR_PIPE_CONNECTED
:
376 waiting_connect_
= false;
379 // The pipe is being closed.
389 bool ChannelWin::ProcessOutgoingMessages(
390 base::MessageLoopForIO::IOContext
* context
,
391 DWORD bytes_written
) {
392 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
394 DCHECK(thread_check_
->CalledOnValidThread());
396 if (output_state_
.is_pending
) {
398 output_state_
.is_pending
= false;
399 if (!context
|| bytes_written
== 0) {
400 DWORD err
= GetLastError();
401 LOG(ERROR
) << "pipe error: " << err
;
405 CHECK(!output_queue_
.empty());
406 Message
* m
= output_queue_
.front();
411 if (output_queue_
.empty())
414 if (!pipe_
.IsValid())
418 Message
* m
= output_queue_
.front();
419 DCHECK(m
->size() <= INT_MAX
);
420 BOOL ok
= WriteFile(pipe_
.Get(),
422 static_cast<uint32
>(m
->size()),
424 &output_state_
.context
.overlapped
);
426 DWORD write_error
= GetLastError();
427 if (write_error
== ERROR_IO_PENDING
) {
428 output_state_
.is_pending
= true;
430 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
431 << " with type " << m
->type();
435 LOG(ERROR
) << "pipe error: " << write_error
;
439 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
440 << " with type " << m
->type();
442 output_state_
.is_pending
= true;
446 void ChannelWin::OnIOCompleted(
447 base::MessageLoopForIO::IOContext
* context
,
448 DWORD bytes_transfered
,
451 DCHECK(thread_check_
->CalledOnValidThread());
452 if (context
== &input_state_
.context
) {
453 if (waiting_connect_
) {
454 if (!ProcessConnection())
456 // We may have some messages queued up to send...
457 if (!output_queue_
.empty() && !output_state_
.is_pending
)
458 ProcessOutgoingMessages(NULL
, 0);
459 if (input_state_
.is_pending
)
461 // else, fall-through and look for incoming messages...
464 // We don't support recursion through OnMessageReceived yet!
465 DCHECK(!processing_incoming_
);
466 base::AutoReset
<bool> auto_reset_processing_incoming(
467 &processing_incoming_
, true);
469 // Process the new data.
470 if (input_state_
.is_pending
) {
471 // This is the normal case for everything except the initialization step.
472 input_state_
.is_pending
= false;
473 if (!bytes_transfered
)
475 else if (pipe_
.IsValid())
476 ok
= AsyncReadComplete(bytes_transfered
);
478 DCHECK(!bytes_transfered
);
481 // Request more data.
483 ok
= ProcessIncomingMessages();
485 DCHECK(context
== &output_state_
.context
);
486 CHECK(output_state_
.is_pending
);
487 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
489 if (!ok
&& pipe_
.IsValid()) {
490 // We don't want to re-enter Close().
492 listener()->OnChannelError();
496 //------------------------------------------------------------------------------
500 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
503 AttachmentBroker
* broker
) {
504 return scoped_ptr
<Channel
>(
505 new ChannelWin(channel_handle
, mode
, listener
, broker
));
509 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
510 return ChannelWin::IsNamedServerInitialized(channel_id
);
514 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
515 // Windows pipes can be enumerated by low-privileged processes. So, we
516 // append a strong random value after the \ character. This value is not
517 // included in the pipe name, but sent as part of the client hello, to
518 // hijacking the pipe name to spoof the client.
520 std::string id
= prefix
;
525 do { // Guarantee we get a non-zero value.
526 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
527 } while (secret
== 0);
529 id
.append(GenerateUniqueRandomChannelID());
530 return id
.append(base::StringPrintf("\\%d", secret
));