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"
10 #include "base/auto_reset.h"
11 #include "base/bind.h"
12 #include "base/compiler_specific.h"
13 #include "base/logging.h"
14 #include "base/pickle.h"
15 #include "base/process/process_handle.h"
16 #include "base/rand_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/threading/thread_checker.h"
20 #include "base/win/scoped_handle.h"
21 #include "ipc/ipc_listener.h"
22 #include "ipc/ipc_logging.h"
23 #include "ipc/ipc_message_attachment_set.h"
24 #include "ipc/ipc_message_utils.h"
28 ChannelWin::State::State(ChannelWin
* channel
) : is_pending(false) {
29 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
30 context
.handler
= channel
;
33 ChannelWin::State::~State() {
34 static_assert(offsetof(ChannelWin::State
, context
) == 0,
35 "ChannelWin::State should have context as its first data"
39 ChannelWin::ChannelWin(const IPC::ChannelHandle
& channel_handle
,
42 AttachmentBroker
* broker
)
43 : ChannelReader(listener
),
46 peer_pid_(base::kNullProcessId
),
47 waiting_connect_(mode
& MODE_SERVER_FLAG
),
48 processing_incoming_(false),
49 validate_client_(false),
53 CreatePipe(channel_handle
, mode
);
56 ChannelWin::~ChannelWin() {
60 void ChannelWin::Close() {
61 if (thread_check_
.get())
62 DCHECK(thread_check_
->CalledOnValidThread());
64 if (input_state_
.is_pending
|| output_state_
.is_pending
)
65 CancelIo(pipe_
.Get());
67 // Closing the handle at this point prevents us from issuing more requests
68 // form OnIOCompleted().
72 // Make sure all IO has completed.
73 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
74 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
77 while (!output_queue_
.empty()) {
78 Message
* m
= output_queue_
.front();
84 bool ChannelWin::Send(Message
* message
) {
85 DCHECK(thread_check_
->CalledOnValidThread());
86 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
87 << " with type " << message
->type()
88 << " (" << output_queue_
.size() << " in queue)";
90 if (!prelim_queue_
.empty()) {
91 prelim_queue_
.push(message
);
95 if (message
->HasBrokerableAttachments() &&
96 peer_pid_
== base::kNullProcessId
) {
97 prelim_queue_
.push(message
);
101 return ProcessMessageForDelivery(message
);
104 bool ChannelWin::ProcessMessageForDelivery(Message
* message
) {
105 // Sending a brokerable attachment requires a call to Channel::Send(), so
106 // both Send() and ProcessMessageForDelivery() may be re-entrant. Brokered
107 // attachments must be sent before the Message itself.
108 if (message
->HasBrokerableAttachments()) {
110 DCHECK(peer_pid_
!= base::kNullProcessId
);
111 for (const BrokerableAttachment
* attachment
:
112 message
->attachment_set()->PeekBrokerableAttachments()) {
113 if (!broker_
->SendAttachmentToProcess(attachment
, peer_pid_
)) {
120 #ifdef IPC_MESSAGE_LOG_ENABLED
121 Logging::GetInstance()->OnSendMessage(message
, "");
124 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
125 "ChannelWin::ProcessMessageForDelivery",
127 TRACE_EVENT_FLAG_FLOW_OUT
);
129 // |output_queue_| takes ownership of |message|.
130 output_queue_
.push(message
);
131 // ensure waiting to write
132 if (!waiting_connect_
) {
133 if (!output_state_
.is_pending
) {
134 if (!ProcessOutgoingMessages(NULL
, 0))
142 void ChannelWin::FlushPrelimQueue() {
143 DCHECK_NE(peer_pid_
, base::kNullProcessId
);
145 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
146 // is critical that |prelim_queue_| appears empty.
147 std::queue
<Message
*> prelim_queue
;
148 prelim_queue_
.swap(prelim_queue
);
150 while (!prelim_queue
.empty()) {
151 Message
* m
= prelim_queue
.front();
152 ProcessMessageForDelivery(m
);
157 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
161 base::ProcessId
ChannelWin::GetPeerPID() const {
165 base::ProcessId
ChannelWin::GetSelfPID() const {
166 return GetCurrentProcessId();
170 bool ChannelWin::IsNamedServerInitialized(
171 const std::string
& channel_id
) {
172 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
174 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
176 return GetLastError() == ERROR_SEM_TIMEOUT
;
179 ChannelWin::ReadState
ChannelWin::ReadData(
182 int* /* bytes_read */) {
183 if (!pipe_
.IsValid())
186 DWORD bytes_read
= 0;
187 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
188 &bytes_read
, &input_state_
.context
.overlapped
);
190 DWORD err
= GetLastError();
191 if (err
== ERROR_IO_PENDING
) {
192 input_state_
.is_pending
= true;
195 LOG(ERROR
) << "pipe error: " << err
;
199 // We could return READ_SUCCEEDED here. But the way that this code is
200 // structured we instead go back to the message loop. Our completion port
201 // will be signalled even in the "synchronously completed" state.
203 // This allows us to potentially process some outgoing messages and
204 // interleave other work on this thread when we're getting hammered with
205 // input messages. Potentially, this could be tuned to be more efficient
206 // with some testing.
207 input_state_
.is_pending
= true;
211 bool ChannelWin::ShouldDispatchInputMessage(Message
* msg
) {
212 // Make sure we get a hello when client validation is required.
213 if (validate_client_
)
214 return IsHelloMessage(*msg
);
218 bool ChannelWin::GetNonBrokeredAttachments(Message
* msg
) {
222 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
223 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
224 // The hello message contains one parameter containing the PID.
225 base::PickleIterator
it(msg
);
227 bool failed
= !it
.ReadInt(&claimed_pid
);
229 if (!failed
&& validate_client_
) {
231 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
237 listener()->OnChannelError();
241 peer_pid_
= claimed_pid
;
242 // Validation completed.
243 validate_client_
= false;
247 listener()->OnChannelConnected(claimed_pid
);
250 base::ProcessId
ChannelWin::GetSenderPID() {
254 bool ChannelWin::IsAttachmentBrokerEndpoint() {
255 return is_attachment_broker_endpoint();
258 bool ChannelWin::DidEmptyInputBuffers() {
259 // We don't need to do anything here.
264 const base::string16
ChannelWin::PipeName(const std::string
& channel_id
,
266 std::string
name("\\\\.\\pipe\\chrome.");
268 // Prevent the shared secret from ending up in the pipe name.
269 size_t index
= channel_id
.find_first_of('\\');
270 if (index
!= std::string::npos
) {
271 if (secret
) // Retrieve the secret if asked for.
272 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
273 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
276 // This case is here to support predictable named pipes in tests.
279 return base::ASCIIToUTF16(name
.append(channel_id
));
282 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
284 DCHECK(!pipe_
.IsValid());
285 base::string16 pipe_name
;
286 // If we already have a valid pipe for channel just copy it.
287 if (channel_handle
.pipe
.handle
) {
288 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
289 // favor of two independent entities (name/file), or it should be a move-
290 // only type with a base::File member. In any case, this code should not
291 // call DuplicateHandle.
292 DCHECK(channel_handle
.name
.empty());
293 pipe_name
= L
"Not Available"; // Just used for LOG
294 // Check that the given pipe confirms to the specified mode. We can
295 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
296 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
298 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
299 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
300 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
301 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
302 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
306 if (!DuplicateHandle(GetCurrentProcess(),
307 channel_handle
.pipe
.handle
,
312 DUPLICATE_SAME_ACCESS
)) {
313 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
316 pipe_
.Set(local_handle
);
317 } else if (mode
& MODE_SERVER_FLAG
) {
318 DCHECK(!channel_handle
.pipe
.handle
);
319 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
320 FILE_FLAG_FIRST_PIPE_INSTANCE
;
321 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
322 validate_client_
= !!client_secret_
;
323 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
325 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
327 Channel::kReadBufferSize
,
328 Channel::kReadBufferSize
,
331 } else if (mode
& MODE_CLIENT_FLAG
) {
332 DCHECK(!channel_handle
.pipe
.handle
);
333 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
334 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
335 GENERIC_READ
| GENERIC_WRITE
,
339 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
340 FILE_FLAG_OVERLAPPED
,
346 if (!pipe_
.IsValid()) {
347 // If this process is being closed, the pipe may be gone already.
348 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
349 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
353 // Create the Hello message to be sent when Connect is called
354 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
356 IPC::Message::PRIORITY_NORMAL
));
358 // Don't send the secret to the untrusted process, and don't send a secret
359 // if the value is zero (for IPC backwards compatability).
360 int32_t secret
= validate_client_
? 0 : client_secret_
;
361 if (!m
->WriteInt(GetCurrentProcessId()) ||
362 (secret
&& !m
->WriteUInt32(secret
))) {
367 output_queue_
.push(m
.release());
371 bool ChannelWin::Connect() {
372 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
374 if (!thread_check_
.get())
375 thread_check_
.reset(new base::ThreadChecker());
377 if (!pipe_
.IsValid())
380 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
382 // Check to see if there is a client connected to our pipe...
383 if (waiting_connect_
)
386 if (!input_state_
.is_pending
) {
387 // Complete setup asynchronously. By not setting input_state_.is_pending
388 // to true, we indicate to OnIOCompleted that this is the special
389 // initialization signal.
390 base::MessageLoopForIO::current()->PostTask(
392 base::Bind(&ChannelWin::OnIOCompleted
,
393 weak_factory_
.GetWeakPtr(),
394 &input_state_
.context
,
399 if (!waiting_connect_
)
400 ProcessOutgoingMessages(NULL
, 0);
404 bool ChannelWin::ProcessConnection() {
405 DCHECK(thread_check_
->CalledOnValidThread());
406 if (input_state_
.is_pending
)
407 input_state_
.is_pending
= false;
409 // Do we have a client connected to our pipe?
410 if (!pipe_
.IsValid())
413 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
414 DWORD err
= GetLastError();
416 // Uhm, the API documentation says that this function should never
417 // return success when used in overlapped mode.
423 case ERROR_IO_PENDING
:
424 input_state_
.is_pending
= true;
426 case ERROR_PIPE_CONNECTED
:
427 waiting_connect_
= false;
430 // The pipe is being closed.
440 bool ChannelWin::ProcessOutgoingMessages(
441 base::MessageLoopForIO::IOContext
* context
,
442 DWORD bytes_written
) {
443 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
445 DCHECK(thread_check_
->CalledOnValidThread());
447 if (output_state_
.is_pending
) {
449 output_state_
.is_pending
= false;
450 if (!context
|| bytes_written
== 0) {
451 DWORD err
= GetLastError();
452 LOG(ERROR
) << "pipe error: " << err
;
456 CHECK(!output_queue_
.empty());
457 Message
* m
= output_queue_
.front();
462 if (output_queue_
.empty())
465 if (!pipe_
.IsValid())
469 Message
* m
= output_queue_
.front();
470 DCHECK(m
->size() <= INT_MAX
);
471 BOOL ok
= WriteFile(pipe_
.Get(),
473 static_cast<uint32_t>(m
->size()),
475 &output_state_
.context
.overlapped
);
477 DWORD write_error
= GetLastError();
478 if (write_error
== ERROR_IO_PENDING
) {
479 output_state_
.is_pending
= true;
481 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
482 << " with type " << m
->type();
486 LOG(ERROR
) << "pipe error: " << write_error
;
490 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
491 << " with type " << m
->type();
493 output_state_
.is_pending
= true;
497 void ChannelWin::OnIOCompleted(
498 base::MessageLoopForIO::IOContext
* context
,
499 DWORD bytes_transfered
,
502 DCHECK(thread_check_
->CalledOnValidThread());
503 if (context
== &input_state_
.context
) {
504 if (waiting_connect_
) {
505 if (!ProcessConnection())
507 // We may have some messages queued up to send...
508 if (!output_queue_
.empty() && !output_state_
.is_pending
)
509 ProcessOutgoingMessages(NULL
, 0);
510 if (input_state_
.is_pending
)
512 // else, fall-through and look for incoming messages...
515 // We don't support recursion through OnMessageReceived yet!
516 DCHECK(!processing_incoming_
);
517 base::AutoReset
<bool> auto_reset_processing_incoming(
518 &processing_incoming_
, true);
520 // Process the new data.
521 if (input_state_
.is_pending
) {
522 // This is the normal case for everything except the initialization step.
523 input_state_
.is_pending
= false;
524 if (!bytes_transfered
) {
526 } else if (pipe_
.IsValid()) {
527 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
530 DCHECK(!bytes_transfered
);
533 // Request more data.
535 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
537 DCHECK(context
== &output_state_
.context
);
538 CHECK(output_state_
.is_pending
);
539 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
541 if (!ok
&& pipe_
.IsValid()) {
542 // We don't want to re-enter Close().
544 listener()->OnChannelError();
548 //------------------------------------------------------------------------------
552 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
555 AttachmentBroker
* broker
) {
556 return scoped_ptr
<Channel
>(
557 new ChannelWin(channel_handle
, mode
, listener
, broker
));
561 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
562 return ChannelWin::IsNamedServerInitialized(channel_id
);
566 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
567 // Windows pipes can be enumerated by low-privileged processes. So, we
568 // append a strong random value after the \ character. This value is not
569 // included in the pipe name, but sent as part of the client hello, to
570 // hijacking the pipe name to spoof the client.
572 std::string id
= prefix
;
577 do { // Guarantee we get a non-zero value.
578 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
579 } while (secret
== 0);
581 id
.append(GenerateUniqueRandomChannelID());
582 return id
.append(base::StringPrintf("\\%d", secret
));