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() {
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 OutputElement
* element
= 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 OutputElement
* element
= new OutputElement(message
);
131 output_queue_
.push(element
);
133 #if USE_ATTACHMENT_BROKER
134 if (message
->HasBrokerableAttachments()) {
135 // |output_queue_| takes ownership of |ids.buffer|.
136 Message::SerializedAttachmentIds ids
=
137 message
->SerializedIdsOfBrokerableAttachments();
138 OutputElement
* new_element
= new OutputElement(ids
.buffer
, ids
.size
);
139 output_queue_
.push(new_element
);
143 // ensure waiting to write
144 if (!waiting_connect_
) {
145 if (!output_state_
.is_pending
) {
146 if (!ProcessOutgoingMessages(NULL
, 0))
154 void ChannelWin::FlushPrelimQueue() {
155 DCHECK_NE(peer_pid_
, base::kNullProcessId
);
157 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
158 // is critical that |prelim_queue_| appears empty.
159 std::queue
<Message
*> prelim_queue
;
160 prelim_queue_
.swap(prelim_queue
);
162 while (!prelim_queue
.empty()) {
163 Message
* m
= prelim_queue
.front();
164 ProcessMessageForDelivery(m
);
169 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
173 base::ProcessId
ChannelWin::GetPeerPID() const {
177 base::ProcessId
ChannelWin::GetSelfPID() const {
178 return GetCurrentProcessId();
182 bool ChannelWin::IsNamedServerInitialized(
183 const std::string
& channel_id
) {
184 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
186 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
188 return GetLastError() == ERROR_SEM_TIMEOUT
;
191 ChannelWin::ReadState
ChannelWin::ReadData(
194 int* /* bytes_read */) {
195 if (!pipe_
.IsValid())
198 DWORD bytes_read
= 0;
199 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
200 &bytes_read
, &input_state_
.context
.overlapped
);
202 DWORD err
= GetLastError();
203 if (err
== ERROR_IO_PENDING
) {
204 input_state_
.is_pending
= true;
207 LOG(ERROR
) << "pipe error: " << err
;
211 // We could return READ_SUCCEEDED here. But the way that this code is
212 // structured we instead go back to the message loop. Our completion port
213 // will be signalled even in the "synchronously completed" state.
215 // This allows us to potentially process some outgoing messages and
216 // interleave other work on this thread when we're getting hammered with
217 // input messages. Potentially, this could be tuned to be more efficient
218 // with some testing.
219 input_state_
.is_pending
= true;
223 bool ChannelWin::ShouldDispatchInputMessage(Message
* msg
) {
224 // Make sure we get a hello when client validation is required.
225 if (validate_client_
)
226 return IsHelloMessage(*msg
);
230 bool ChannelWin::GetNonBrokeredAttachments(Message
* msg
) {
234 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
235 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
236 // The hello message contains one parameter containing the PID.
237 base::PickleIterator
it(msg
);
239 bool failed
= !it
.ReadInt(&claimed_pid
);
241 if (!failed
&& validate_client_
) {
243 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
249 listener()->OnChannelError();
253 peer_pid_
= claimed_pid
;
254 // Validation completed.
255 validate_client_
= false;
259 listener()->OnChannelConnected(claimed_pid
);
262 base::ProcessId
ChannelWin::GetSenderPID() {
266 bool ChannelWin::IsAttachmentBrokerEndpoint() {
267 return is_attachment_broker_endpoint();
270 bool ChannelWin::DidEmptyInputBuffers() {
271 // We don't need to do anything here.
276 const base::string16
ChannelWin::PipeName(
277 const std::string
& channel_id
, int32
* secret
) {
278 std::string
name("\\\\.\\pipe\\chrome.");
280 // Prevent the shared secret from ending up in the pipe name.
281 size_t index
= channel_id
.find_first_of('\\');
282 if (index
!= std::string::npos
) {
283 if (secret
) // Retrieve the secret if asked for.
284 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
285 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
288 // This case is here to support predictable named pipes in tests.
291 return base::ASCIIToUTF16(name
.append(channel_id
));
294 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
296 DCHECK(!pipe_
.IsValid());
297 base::string16 pipe_name
;
298 // If we already have a valid pipe for channel just copy it.
299 if (channel_handle
.pipe
.handle
) {
300 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
301 // favor of two independent entities (name/file), or it should be a move-
302 // only type with a base::File member. In any case, this code should not
303 // call DuplicateHandle.
304 DCHECK(channel_handle
.name
.empty());
305 pipe_name
= L
"Not Available"; // Just used for LOG
306 // Check that the given pipe confirms to the specified mode. We can
307 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
308 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
310 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
311 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
312 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
313 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
314 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
318 if (!DuplicateHandle(GetCurrentProcess(),
319 channel_handle
.pipe
.handle
,
324 DUPLICATE_SAME_ACCESS
)) {
325 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
328 pipe_
.Set(local_handle
);
329 } else if (mode
& MODE_SERVER_FLAG
) {
330 DCHECK(!channel_handle
.pipe
.handle
);
331 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
332 FILE_FLAG_FIRST_PIPE_INSTANCE
;
333 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
334 validate_client_
= !!client_secret_
;
335 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
337 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
339 Channel::kReadBufferSize
,
340 Channel::kReadBufferSize
,
343 } else if (mode
& MODE_CLIENT_FLAG
) {
344 DCHECK(!channel_handle
.pipe
.handle
);
345 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
346 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
347 GENERIC_READ
| GENERIC_WRITE
,
351 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
352 FILE_FLAG_OVERLAPPED
,
358 if (!pipe_
.IsValid()) {
359 // If this process is being closed, the pipe may be gone already.
360 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
361 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
365 // Create the Hello message to be sent when Connect is called
366 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
368 IPC::Message::PRIORITY_NORMAL
));
370 // Don't send the secret to the untrusted process, and don't send a secret
371 // if the value is zero (for IPC backwards compatability).
372 int32 secret
= validate_client_
? 0 : client_secret_
;
373 if (!m
->WriteInt(GetCurrentProcessId()) ||
374 (secret
&& !m
->WriteUInt32(secret
))) {
379 OutputElement
* element
= new OutputElement(m
.release());
380 output_queue_
.push(element
);
384 bool ChannelWin::Connect() {
385 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
387 if (!thread_check_
.get())
388 thread_check_
.reset(new base::ThreadChecker());
390 if (!pipe_
.IsValid())
393 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
395 // Check to see if there is a client connected to our pipe...
396 if (waiting_connect_
)
399 if (!input_state_
.is_pending
) {
400 // Complete setup asynchronously. By not setting input_state_.is_pending
401 // to true, we indicate to OnIOCompleted that this is the special
402 // initialization signal.
403 base::MessageLoopForIO::current()->PostTask(
405 base::Bind(&ChannelWin::OnIOCompleted
,
406 weak_factory_
.GetWeakPtr(),
407 &input_state_
.context
,
412 if (!waiting_connect_
)
413 ProcessOutgoingMessages(NULL
, 0);
417 bool ChannelWin::ProcessConnection() {
418 DCHECK(thread_check_
->CalledOnValidThread());
419 if (input_state_
.is_pending
)
420 input_state_
.is_pending
= false;
422 // Do we have a client connected to our pipe?
423 if (!pipe_
.IsValid())
426 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
427 DWORD err
= GetLastError();
429 // Uhm, the API documentation says that this function should never
430 // return success when used in overlapped mode.
436 case ERROR_IO_PENDING
:
437 input_state_
.is_pending
= true;
439 case ERROR_PIPE_CONNECTED
:
440 waiting_connect_
= false;
443 // The pipe is being closed.
453 bool ChannelWin::ProcessOutgoingMessages(
454 base::MessageLoopForIO::IOContext
* context
,
455 DWORD bytes_written
) {
456 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
458 DCHECK(thread_check_
->CalledOnValidThread());
460 if (output_state_
.is_pending
) {
462 output_state_
.is_pending
= false;
463 if (!context
|| bytes_written
== 0) {
464 DWORD err
= GetLastError();
465 LOG(ERROR
) << "pipe error: " << err
;
469 CHECK(!output_queue_
.empty());
470 OutputElement
* element
= output_queue_
.front();
475 if (output_queue_
.empty())
478 if (!pipe_
.IsValid())
482 OutputElement
* element
= output_queue_
.front();
483 DCHECK(element
->size() <= INT_MAX
);
484 BOOL ok
= WriteFile(pipe_
.Get(), element
->data(),
485 static_cast<uint32
>(element
->size()), NULL
,
486 &output_state_
.context
.overlapped
);
488 DWORD write_error
= GetLastError();
489 if (write_error
== ERROR_IO_PENDING
) {
490 output_state_
.is_pending
= true;
492 const Message
* m
= element
->get_message();
494 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
495 << " with type " << m
->type();
500 LOG(ERROR
) << "pipe error: " << write_error
;
504 const Message
* m
= element
->get_message();
506 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
507 << " with type " << m
->type();
510 output_state_
.is_pending
= true;
514 void ChannelWin::OnIOCompleted(
515 base::MessageLoopForIO::IOContext
* context
,
516 DWORD bytes_transfered
,
519 DCHECK(thread_check_
->CalledOnValidThread());
520 if (context
== &input_state_
.context
) {
521 if (waiting_connect_
) {
522 if (!ProcessConnection())
524 // We may have some messages queued up to send...
525 if (!output_queue_
.empty() && !output_state_
.is_pending
)
526 ProcessOutgoingMessages(NULL
, 0);
527 if (input_state_
.is_pending
)
529 // else, fall-through and look for incoming messages...
532 // We don't support recursion through OnMessageReceived yet!
533 DCHECK(!processing_incoming_
);
534 base::AutoReset
<bool> auto_reset_processing_incoming(
535 &processing_incoming_
, true);
537 // Process the new data.
538 if (input_state_
.is_pending
) {
539 // This is the normal case for everything except the initialization step.
540 input_state_
.is_pending
= false;
541 if (!bytes_transfered
) {
543 } else if (pipe_
.IsValid()) {
544 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
547 DCHECK(!bytes_transfered
);
550 // Request more data.
552 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
554 DCHECK(context
== &output_state_
.context
);
555 CHECK(output_state_
.is_pending
);
556 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
558 if (!ok
&& pipe_
.IsValid()) {
559 // We don't want to re-enter Close().
561 listener()->OnChannelError();
565 //------------------------------------------------------------------------------
569 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
572 AttachmentBroker
* broker
) {
573 return scoped_ptr
<Channel
>(
574 new ChannelWin(channel_handle
, mode
, listener
, broker
));
578 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
579 return ChannelWin::IsNamedServerInitialized(channel_id
);
583 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
584 // Windows pipes can be enumerated by low-privileged processes. So, we
585 // append a strong random value after the \ character. This value is not
586 // included in the pipe name, but sent as part of the client hello, to
587 // hijacking the pipe name to spoof the client.
589 std::string id
= prefix
;
594 do { // Guarantee we get a non-zero value.
595 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
596 } while (secret
== 0);
598 id
.append(GenerateUniqueRandomChannelID());
599 return id
.append(base::StringPrintf("\\%d", secret
));