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 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 // TODO(erikchen): Serialize the brokerable attachments and add them to the
134 // output_queue_. http://crbug.com/493414.
136 // ensure waiting to write
137 if (!waiting_connect_
) {
138 if (!output_state_
.is_pending
) {
139 if (!ProcessOutgoingMessages(NULL
, 0))
147 void ChannelWin::FlushPrelimQueue() {
148 DCHECK_NE(peer_pid_
, base::kNullProcessId
);
150 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
151 // is critical that |prelim_queue_| appears empty.
152 std::queue
<Message
*> prelim_queue
;
153 prelim_queue_
.swap(prelim_queue
);
155 while (!prelim_queue
.empty()) {
156 Message
* m
= prelim_queue
.front();
157 ProcessMessageForDelivery(m
);
162 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
166 base::ProcessId
ChannelWin::GetPeerPID() const {
170 base::ProcessId
ChannelWin::GetSelfPID() const {
171 return GetCurrentProcessId();
175 bool ChannelWin::IsNamedServerInitialized(
176 const std::string
& channel_id
) {
177 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
179 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
181 return GetLastError() == ERROR_SEM_TIMEOUT
;
184 ChannelWin::ReadState
ChannelWin::ReadData(
187 int* /* bytes_read */) {
188 if (!pipe_
.IsValid())
191 DWORD bytes_read
= 0;
192 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
193 &bytes_read
, &input_state_
.context
.overlapped
);
195 DWORD err
= GetLastError();
196 if (err
== ERROR_IO_PENDING
) {
197 input_state_
.is_pending
= true;
200 LOG(ERROR
) << "pipe error: " << err
;
204 // We could return READ_SUCCEEDED here. But the way that this code is
205 // structured we instead go back to the message loop. Our completion port
206 // will be signalled even in the "synchronously completed" state.
208 // This allows us to potentially process some outgoing messages and
209 // interleave other work on this thread when we're getting hammered with
210 // input messages. Potentially, this could be tuned to be more efficient
211 // with some testing.
212 input_state_
.is_pending
= true;
216 bool ChannelWin::ShouldDispatchInputMessage(Message
* msg
) {
217 // Make sure we get a hello when client validation is required.
218 if (validate_client_
)
219 return IsHelloMessage(*msg
);
223 bool ChannelWin::GetNonBrokeredAttachments(Message
* msg
) {
227 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
228 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
229 // The hello message contains one parameter containing the PID.
230 base::PickleIterator
it(msg
);
232 bool failed
= !it
.ReadInt(&claimed_pid
);
234 if (!failed
&& validate_client_
) {
236 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
242 listener()->OnChannelError();
246 peer_pid_
= claimed_pid
;
247 // Validation completed.
248 validate_client_
= false;
252 listener()->OnChannelConnected(claimed_pid
);
255 base::ProcessId
ChannelWin::GetSenderPID() {
259 bool ChannelWin::IsAttachmentBrokerEndpoint() {
260 return is_attachment_broker_endpoint();
263 bool ChannelWin::DidEmptyInputBuffers() {
264 // We don't need to do anything here.
269 const base::string16
ChannelWin::PipeName(const std::string
& channel_id
,
271 std::string
name("\\\\.\\pipe\\chrome.");
273 // Prevent the shared secret from ending up in the pipe name.
274 size_t index
= channel_id
.find_first_of('\\');
275 if (index
!= std::string::npos
) {
276 if (secret
) // Retrieve the secret if asked for.
277 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
278 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
281 // This case is here to support predictable named pipes in tests.
284 return base::ASCIIToUTF16(name
.append(channel_id
));
287 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
289 DCHECK(!pipe_
.IsValid());
290 base::string16 pipe_name
;
291 // If we already have a valid pipe for channel just copy it.
292 if (channel_handle
.pipe
.handle
) {
293 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
294 // favor of two independent entities (name/file), or it should be a move-
295 // only type with a base::File member. In any case, this code should not
296 // call DuplicateHandle.
297 DCHECK(channel_handle
.name
.empty());
298 pipe_name
= L
"Not Available"; // Just used for LOG
299 // Check that the given pipe confirms to the specified mode. We can
300 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
301 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
303 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
304 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
305 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
306 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
307 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
311 if (!DuplicateHandle(GetCurrentProcess(),
312 channel_handle
.pipe
.handle
,
317 DUPLICATE_SAME_ACCESS
)) {
318 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
321 pipe_
.Set(local_handle
);
322 } else if (mode
& MODE_SERVER_FLAG
) {
323 DCHECK(!channel_handle
.pipe
.handle
);
324 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
325 FILE_FLAG_FIRST_PIPE_INSTANCE
;
326 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
327 validate_client_
= !!client_secret_
;
328 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
330 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
332 Channel::kReadBufferSize
,
333 Channel::kReadBufferSize
,
336 } else if (mode
& MODE_CLIENT_FLAG
) {
337 DCHECK(!channel_handle
.pipe
.handle
);
338 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
339 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
340 GENERIC_READ
| GENERIC_WRITE
,
344 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
345 FILE_FLAG_OVERLAPPED
,
351 if (!pipe_
.IsValid()) {
352 // If this process is being closed, the pipe may be gone already.
353 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
354 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
358 // Create the Hello message to be sent when Connect is called
359 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
361 IPC::Message::PRIORITY_NORMAL
));
363 // Don't send the secret to the untrusted process, and don't send a secret
364 // if the value is zero (for IPC backwards compatability).
365 int32_t secret
= validate_client_
? 0 : client_secret_
;
366 if (!m
->WriteInt(GetCurrentProcessId()) ||
367 (secret
&& !m
->WriteUInt32(secret
))) {
372 OutputElement
* element
= new OutputElement(m
.release());
373 output_queue_
.push(element
);
377 bool ChannelWin::Connect() {
378 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
380 if (!thread_check_
.get())
381 thread_check_
.reset(new base::ThreadChecker());
383 if (!pipe_
.IsValid())
386 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
388 // Check to see if there is a client connected to our pipe...
389 if (waiting_connect_
)
392 if (!input_state_
.is_pending
) {
393 // Complete setup asynchronously. By not setting input_state_.is_pending
394 // to true, we indicate to OnIOCompleted that this is the special
395 // initialization signal.
396 base::MessageLoopForIO::current()->PostTask(
398 base::Bind(&ChannelWin::OnIOCompleted
,
399 weak_factory_
.GetWeakPtr(),
400 &input_state_
.context
,
405 if (!waiting_connect_
)
406 ProcessOutgoingMessages(NULL
, 0);
410 bool ChannelWin::ProcessConnection() {
411 DCHECK(thread_check_
->CalledOnValidThread());
412 if (input_state_
.is_pending
)
413 input_state_
.is_pending
= false;
415 // Do we have a client connected to our pipe?
416 if (!pipe_
.IsValid())
419 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
420 DWORD err
= GetLastError();
422 // Uhm, the API documentation says that this function should never
423 // return success when used in overlapped mode.
429 case ERROR_IO_PENDING
:
430 input_state_
.is_pending
= true;
432 case ERROR_PIPE_CONNECTED
:
433 waiting_connect_
= false;
436 // The pipe is being closed.
446 bool ChannelWin::ProcessOutgoingMessages(
447 base::MessageLoopForIO::IOContext
* context
,
448 DWORD bytes_written
) {
449 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
451 DCHECK(thread_check_
->CalledOnValidThread());
453 if (output_state_
.is_pending
) {
455 output_state_
.is_pending
= false;
456 if (!context
|| bytes_written
== 0) {
457 DWORD err
= GetLastError();
458 LOG(ERROR
) << "pipe error: " << err
;
462 CHECK(!output_queue_
.empty());
463 OutputElement
* element
= output_queue_
.front();
468 if (output_queue_
.empty())
471 if (!pipe_
.IsValid())
475 OutputElement
* element
= output_queue_
.front();
476 DCHECK(element
->size() <= INT_MAX
);
477 BOOL ok
= WriteFile(pipe_
.Get(),
479 static_cast<uint32_t>(element
->size()),
481 &output_state_
.context
.overlapped
);
483 DWORD write_error
= GetLastError();
484 if (write_error
== ERROR_IO_PENDING
) {
485 output_state_
.is_pending
= true;
487 const Message
* m
= element
->get_message();
489 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
490 << " with type " << m
->type();
495 LOG(ERROR
) << "pipe error: " << write_error
;
499 const Message
* m
= element
->get_message();
501 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
502 << " with type " << m
->type();
505 output_state_
.is_pending
= true;
509 void ChannelWin::OnIOCompleted(
510 base::MessageLoopForIO::IOContext
* context
,
511 DWORD bytes_transfered
,
514 DCHECK(thread_check_
->CalledOnValidThread());
515 if (context
== &input_state_
.context
) {
516 if (waiting_connect_
) {
517 if (!ProcessConnection())
519 // We may have some messages queued up to send...
520 if (!output_queue_
.empty() && !output_state_
.is_pending
)
521 ProcessOutgoingMessages(NULL
, 0);
522 if (input_state_
.is_pending
)
524 // else, fall-through and look for incoming messages...
527 // We don't support recursion through OnMessageReceived yet!
528 DCHECK(!processing_incoming_
);
529 base::AutoReset
<bool> auto_reset_processing_incoming(
530 &processing_incoming_
, true);
532 // Process the new data.
533 if (input_state_
.is_pending
) {
534 // This is the normal case for everything except the initialization step.
535 input_state_
.is_pending
= false;
536 if (!bytes_transfered
) {
538 } else if (pipe_
.IsValid()) {
539 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
542 DCHECK(!bytes_transfered
);
545 // Request more data.
547 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
549 DCHECK(context
== &output_state_
.context
);
550 CHECK(output_state_
.is_pending
);
551 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
553 if (!ok
&& pipe_
.IsValid()) {
554 // We don't want to re-enter Close().
556 listener()->OnChannelError();
560 //------------------------------------------------------------------------------
564 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
567 AttachmentBroker
* broker
) {
568 return scoped_ptr
<Channel
>(
569 new ChannelWin(channel_handle
, mode
, listener
, broker
));
573 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
574 return ChannelWin::IsNamedServerInitialized(channel_id
);
578 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
579 // Windows pipes can be enumerated by low-privileged processes. So, we
580 // append a strong random value after the \ character. This value is not
581 // included in the pipe name, but sent as part of the client hello, to
582 // hijacking the pipe name to spoof the client.
584 std::string id
= prefix
;
589 do { // Guarantee we get a non-zero value.
590 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
591 } while (secret
== 0);
593 id
.append(GenerateUniqueRandomChannelID());
594 return id
.append(base::StringPrintf("\\%d", secret
));