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 DCHECK(thread_check_
->CalledOnValidThread());
85 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
86 << " with type " << message
->type()
87 << " (" << output_queue_
.size() << " in queue)";
89 if (!prelim_queue_
.empty()) {
90 prelim_queue_
.push(message
);
94 if (message
->HasBrokerableAttachments() &&
95 peer_pid_
== base::kNullProcessId
) {
96 prelim_queue_
.push(message
);
100 return ProcessMessageForDelivery(message
);
103 bool ChannelWin::ProcessMessageForDelivery(Message
* message
) {
104 // Sending a brokerable attachment requires a call to Channel::Send(), so
105 // both Send() and ProcessMessageForDelivery() may be re-entrant. Brokered
106 // attachments must be sent before the Message itself.
107 if (message
->HasBrokerableAttachments()) {
109 DCHECK(peer_pid_
!= base::kNullProcessId
);
110 for (const BrokerableAttachment
* attachment
:
111 message
->attachment_set()->PeekBrokerableAttachments()) {
112 if (!broker_
->SendAttachmentToProcess(attachment
, peer_pid_
)) {
119 #ifdef IPC_MESSAGE_LOG_ENABLED
120 Logging::GetInstance()->OnSendMessage(message
, "");
123 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
124 "ChannelWin::ProcessMessageForDelivery",
126 TRACE_EVENT_FLAG_FLOW_OUT
);
128 // |output_queue_| takes ownership of |message|.
129 output_queue_
.push(message
);
130 // ensure waiting to write
131 if (!waiting_connect_
) {
132 if (!output_state_
.is_pending
) {
133 if (!ProcessOutgoingMessages(NULL
, 0))
141 void ChannelWin::FlushPrelimQueue() {
142 DCHECK_NE(peer_pid_
, base::kNullProcessId
);
144 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
145 // is critical that |prelim_queue_| appears empty.
146 std::queue
<Message
*> prelim_queue
;
147 prelim_queue_
.swap(prelim_queue
);
149 while (!prelim_queue
.empty()) {
150 Message
* m
= prelim_queue
.front();
151 ProcessMessageForDelivery(m
);
156 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
160 base::ProcessId
ChannelWin::GetPeerPID() const {
164 base::ProcessId
ChannelWin::GetSelfPID() const {
165 return GetCurrentProcessId();
169 bool ChannelWin::IsNamedServerInitialized(
170 const std::string
& channel_id
) {
171 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
173 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
175 return GetLastError() == ERROR_SEM_TIMEOUT
;
178 ChannelWin::ReadState
ChannelWin::ReadData(
181 int* /* bytes_read */) {
182 if (!pipe_
.IsValid())
185 DWORD bytes_read
= 0;
186 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
187 &bytes_read
, &input_state_
.context
.overlapped
);
189 DWORD err
= GetLastError();
190 if (err
== ERROR_IO_PENDING
) {
191 input_state_
.is_pending
= true;
194 LOG(ERROR
) << "pipe error: " << err
;
198 // We could return READ_SUCCEEDED here. But the way that this code is
199 // structured we instead go back to the message loop. Our completion port
200 // will be signalled even in the "synchronously completed" state.
202 // This allows us to potentially process some outgoing messages and
203 // interleave other work on this thread when we're getting hammered with
204 // input messages. Potentially, this could be tuned to be more efficient
205 // with some testing.
206 input_state_
.is_pending
= true;
210 bool ChannelWin::ShouldDispatchInputMessage(Message
* msg
) {
211 // Make sure we get a hello when client validation is required.
212 if (validate_client_
)
213 return IsHelloMessage(*msg
);
217 bool ChannelWin::GetNonBrokeredAttachments(Message
* msg
) {
221 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
222 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
223 // The hello message contains one parameter containing the PID.
224 base::PickleIterator
it(msg
);
226 bool failed
= !it
.ReadInt(&claimed_pid
);
228 if (!failed
&& validate_client_
) {
230 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
236 listener()->OnChannelError();
240 peer_pid_
= claimed_pid
;
241 // Validation completed.
242 validate_client_
= false;
246 listener()->OnChannelConnected(claimed_pid
);
249 base::ProcessId
ChannelWin::GetSenderPID() {
253 bool ChannelWin::IsAttachmentBrokerEndpoint() {
254 return is_attachment_broker_endpoint();
257 bool ChannelWin::DidEmptyInputBuffers() {
258 // We don't need to do anything here.
263 const base::string16
ChannelWin::PipeName(
264 const std::string
& channel_id
, int32
* secret
) {
265 std::string
name("\\\\.\\pipe\\chrome.");
267 // Prevent the shared secret from ending up in the pipe name.
268 size_t index
= channel_id
.find_first_of('\\');
269 if (index
!= std::string::npos
) {
270 if (secret
) // Retrieve the secret if asked for.
271 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
272 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
275 // This case is here to support predictable named pipes in tests.
278 return base::ASCIIToUTF16(name
.append(channel_id
));
281 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
283 DCHECK(!pipe_
.IsValid());
284 base::string16 pipe_name
;
285 // If we already have a valid pipe for channel just copy it.
286 if (channel_handle
.pipe
.handle
) {
287 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
288 // favor of two independent entities (name/file), or it should be a move-
289 // only type with a base::File member. In any case, this code should not
290 // call DuplicateHandle.
291 DCHECK(channel_handle
.name
.empty());
292 pipe_name
= L
"Not Available"; // Just used for LOG
293 // Check that the given pipe confirms to the specified mode. We can
294 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
295 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
297 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
298 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
299 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
300 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
301 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
305 if (!DuplicateHandle(GetCurrentProcess(),
306 channel_handle
.pipe
.handle
,
311 DUPLICATE_SAME_ACCESS
)) {
312 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
315 pipe_
.Set(local_handle
);
316 } else if (mode
& MODE_SERVER_FLAG
) {
317 DCHECK(!channel_handle
.pipe
.handle
);
318 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
319 FILE_FLAG_FIRST_PIPE_INSTANCE
;
320 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
321 validate_client_
= !!client_secret_
;
322 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
324 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
326 Channel::kReadBufferSize
,
327 Channel::kReadBufferSize
,
330 } else if (mode
& MODE_CLIENT_FLAG
) {
331 DCHECK(!channel_handle
.pipe
.handle
);
332 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
333 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
334 GENERIC_READ
| GENERIC_WRITE
,
338 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
339 FILE_FLAG_OVERLAPPED
,
345 if (!pipe_
.IsValid()) {
346 // If this process is being closed, the pipe may be gone already.
347 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
348 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
352 // Create the Hello message to be sent when Connect is called
353 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
355 IPC::Message::PRIORITY_NORMAL
));
357 // Don't send the secret to the untrusted process, and don't send a secret
358 // if the value is zero (for IPC backwards compatability).
359 int32 secret
= validate_client_
? 0 : client_secret_
;
360 if (!m
->WriteInt(GetCurrentProcessId()) ||
361 (secret
&& !m
->WriteUInt32(secret
))) {
366 output_queue_
.push(m
.release());
370 bool ChannelWin::Connect() {
371 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
373 if (!thread_check_
.get())
374 thread_check_
.reset(new base::ThreadChecker());
376 if (!pipe_
.IsValid())
379 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
381 // Check to see if there is a client connected to our pipe...
382 if (waiting_connect_
)
385 if (!input_state_
.is_pending
) {
386 // Complete setup asynchronously. By not setting input_state_.is_pending
387 // to true, we indicate to OnIOCompleted that this is the special
388 // initialization signal.
389 base::MessageLoopForIO::current()->PostTask(
391 base::Bind(&ChannelWin::OnIOCompleted
,
392 weak_factory_
.GetWeakPtr(),
393 &input_state_
.context
,
398 if (!waiting_connect_
)
399 ProcessOutgoingMessages(NULL
, 0);
403 bool ChannelWin::ProcessConnection() {
404 DCHECK(thread_check_
->CalledOnValidThread());
405 if (input_state_
.is_pending
)
406 input_state_
.is_pending
= false;
408 // Do we have a client connected to our pipe?
409 if (!pipe_
.IsValid())
412 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
413 DWORD err
= GetLastError();
415 // Uhm, the API documentation says that this function should never
416 // return success when used in overlapped mode.
422 case ERROR_IO_PENDING
:
423 input_state_
.is_pending
= true;
425 case ERROR_PIPE_CONNECTED
:
426 waiting_connect_
= false;
429 // The pipe is being closed.
439 bool ChannelWin::ProcessOutgoingMessages(
440 base::MessageLoopForIO::IOContext
* context
,
441 DWORD bytes_written
) {
442 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
444 DCHECK(thread_check_
->CalledOnValidThread());
446 if (output_state_
.is_pending
) {
448 output_state_
.is_pending
= false;
449 if (!context
|| bytes_written
== 0) {
450 DWORD err
= GetLastError();
451 LOG(ERROR
) << "pipe error: " << err
;
455 CHECK(!output_queue_
.empty());
456 Message
* m
= output_queue_
.front();
461 if (output_queue_
.empty())
464 if (!pipe_
.IsValid())
468 Message
* m
= output_queue_
.front();
469 DCHECK(m
->size() <= INT_MAX
);
470 BOOL ok
= WriteFile(pipe_
.Get(),
472 static_cast<uint32
>(m
->size()),
474 &output_state_
.context
.overlapped
);
476 DWORD write_error
= GetLastError();
477 if (write_error
== ERROR_IO_PENDING
) {
478 output_state_
.is_pending
= true;
480 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
481 << " with type " << m
->type();
485 LOG(ERROR
) << "pipe error: " << write_error
;
489 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
490 << " with type " << m
->type();
492 output_state_
.is_pending
= true;
496 void ChannelWin::OnIOCompleted(
497 base::MessageLoopForIO::IOContext
* context
,
498 DWORD bytes_transfered
,
501 DCHECK(thread_check_
->CalledOnValidThread());
502 if (context
== &input_state_
.context
) {
503 if (waiting_connect_
) {
504 if (!ProcessConnection())
506 // We may have some messages queued up to send...
507 if (!output_queue_
.empty() && !output_state_
.is_pending
)
508 ProcessOutgoingMessages(NULL
, 0);
509 if (input_state_
.is_pending
)
511 // else, fall-through and look for incoming messages...
514 // We don't support recursion through OnMessageReceived yet!
515 DCHECK(!processing_incoming_
);
516 base::AutoReset
<bool> auto_reset_processing_incoming(
517 &processing_incoming_
, true);
519 // Process the new data.
520 if (input_state_
.is_pending
) {
521 // This is the normal case for everything except the initialization step.
522 input_state_
.is_pending
= false;
523 if (!bytes_transfered
) {
525 } else if (pipe_
.IsValid()) {
526 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
529 DCHECK(!bytes_transfered
);
532 // Request more data.
534 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
536 DCHECK(context
== &output_state_
.context
);
537 CHECK(output_state_
.is_pending
);
538 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
540 if (!ok
&& pipe_
.IsValid()) {
541 // We don't want to re-enter Close().
543 listener()->OnChannelError();
547 //------------------------------------------------------------------------------
551 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
554 AttachmentBroker
* broker
) {
555 return scoped_ptr
<Channel
>(
556 new ChannelWin(channel_handle
, mode
, listener
, broker
));
560 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
561 return ChannelWin::IsNamedServerInitialized(channel_id
);
565 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
566 // Windows pipes can be enumerated by low-privileged processes. So, we
567 // append a strong random value after the \ character. This value is not
568 // included in the pipe name, but sent as part of the client hello, to
569 // hijacking the pipe name to spoof the client.
571 std::string id
= prefix
;
576 do { // Guarantee we get a non-zero value.
577 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
578 } while (secret
== 0);
580 id
.append(GenerateUniqueRandomChannelID());
581 return id
.append(base::StringPrintf("\\%d", secret
));