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 message
->TraceMessageBegin();
125 // |output_queue_| takes ownership of |message|.
126 output_queue_
.push(message
);
127 // ensure waiting to write
128 if (!waiting_connect_
) {
129 if (!output_state_
.is_pending
) {
130 if (!ProcessOutgoingMessages(NULL
, 0))
138 void ChannelWin::FlushPrelimQueue() {
139 DCHECK_NE(peer_pid_
, base::kNullProcessId
);
141 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
142 // is critical that |prelim_queue_| appears empty.
143 std::queue
<Message
*> prelim_queue
;
144 prelim_queue_
.swap(prelim_queue
);
146 while (!prelim_queue
.empty()) {
147 Message
* m
= prelim_queue
.front();
148 ProcessMessageForDelivery(m
);
153 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
157 base::ProcessId
ChannelWin::GetPeerPID() const {
161 base::ProcessId
ChannelWin::GetSelfPID() const {
162 return GetCurrentProcessId();
166 bool ChannelWin::IsNamedServerInitialized(
167 const std::string
& channel_id
) {
168 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
170 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
172 return GetLastError() == ERROR_SEM_TIMEOUT
;
175 ChannelWin::ReadState
ChannelWin::ReadData(
178 int* /* bytes_read */) {
179 if (!pipe_
.IsValid())
182 DWORD bytes_read
= 0;
183 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
184 &bytes_read
, &input_state_
.context
.overlapped
);
186 DWORD err
= GetLastError();
187 if (err
== ERROR_IO_PENDING
) {
188 input_state_
.is_pending
= true;
191 LOG(ERROR
) << "pipe error: " << err
;
195 // We could return READ_SUCCEEDED here. But the way that this code is
196 // structured we instead go back to the message loop. Our completion port
197 // will be signalled even in the "synchronously completed" state.
199 // This allows us to potentially process some outgoing messages and
200 // interleave other work on this thread when we're getting hammered with
201 // input messages. Potentially, this could be tuned to be more efficient
202 // with some testing.
203 input_state_
.is_pending
= true;
207 bool ChannelWin::ShouldDispatchInputMessage(Message
* msg
) {
208 // Make sure we get a hello when client validation is required.
209 if (validate_client_
)
210 return IsHelloMessage(*msg
);
214 bool ChannelWin::GetNonBrokeredAttachments(Message
* msg
) {
218 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
219 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
220 // The hello message contains one parameter containing the PID.
221 base::PickleIterator
it(msg
);
223 bool failed
= !it
.ReadInt(&claimed_pid
);
225 if (!failed
&& validate_client_
) {
227 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
233 listener()->OnChannelError();
237 peer_pid_
= claimed_pid
;
238 // Validation completed.
239 validate_client_
= false;
243 listener()->OnChannelConnected(claimed_pid
);
246 base::ProcessId
ChannelWin::GetSenderPID() {
250 bool ChannelWin::IsAttachmentBrokerEndpoint() {
251 return is_attachment_broker_endpoint();
254 bool ChannelWin::DidEmptyInputBuffers() {
255 // We don't need to do anything here.
260 const base::string16
ChannelWin::PipeName(
261 const std::string
& channel_id
, int32
* secret
) {
262 std::string
name("\\\\.\\pipe\\chrome.");
264 // Prevent the shared secret from ending up in the pipe name.
265 size_t index
= channel_id
.find_first_of('\\');
266 if (index
!= std::string::npos
) {
267 if (secret
) // Retrieve the secret if asked for.
268 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
269 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
272 // This case is here to support predictable named pipes in tests.
275 return base::ASCIIToUTF16(name
.append(channel_id
));
278 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
280 DCHECK(!pipe_
.IsValid());
281 base::string16 pipe_name
;
282 // If we already have a valid pipe for channel just copy it.
283 if (channel_handle
.pipe
.handle
) {
284 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
285 // favor of two independent entities (name/file), or it should be a move-
286 // only type with a base::File member. In any case, this code should not
287 // call DuplicateHandle.
288 DCHECK(channel_handle
.name
.empty());
289 pipe_name
= L
"Not Available"; // Just used for LOG
290 // Check that the given pipe confirms to the specified mode. We can
291 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
292 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
294 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
295 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
296 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
297 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
298 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
302 if (!DuplicateHandle(GetCurrentProcess(),
303 channel_handle
.pipe
.handle
,
308 DUPLICATE_SAME_ACCESS
)) {
309 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
312 pipe_
.Set(local_handle
);
313 } else if (mode
& MODE_SERVER_FLAG
) {
314 DCHECK(!channel_handle
.pipe
.handle
);
315 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
316 FILE_FLAG_FIRST_PIPE_INSTANCE
;
317 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
318 validate_client_
= !!client_secret_
;
319 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
321 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
323 Channel::kReadBufferSize
,
324 Channel::kReadBufferSize
,
327 } else if (mode
& MODE_CLIENT_FLAG
) {
328 DCHECK(!channel_handle
.pipe
.handle
);
329 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
330 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
331 GENERIC_READ
| GENERIC_WRITE
,
335 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
336 FILE_FLAG_OVERLAPPED
,
342 if (!pipe_
.IsValid()) {
343 // If this process is being closed, the pipe may be gone already.
344 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
345 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
349 // Create the Hello message to be sent when Connect is called
350 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
352 IPC::Message::PRIORITY_NORMAL
));
354 // Don't send the secret to the untrusted process, and don't send a secret
355 // if the value is zero (for IPC backwards compatability).
356 int32 secret
= validate_client_
? 0 : client_secret_
;
357 if (!m
->WriteInt(GetCurrentProcessId()) ||
358 (secret
&& !m
->WriteUInt32(secret
))) {
363 output_queue_
.push(m
.release());
367 bool ChannelWin::Connect() {
368 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
370 if (!thread_check_
.get())
371 thread_check_
.reset(new base::ThreadChecker());
373 if (!pipe_
.IsValid())
376 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
378 // Check to see if there is a client connected to our pipe...
379 if (waiting_connect_
)
382 if (!input_state_
.is_pending
) {
383 // Complete setup asynchronously. By not setting input_state_.is_pending
384 // to true, we indicate to OnIOCompleted that this is the special
385 // initialization signal.
386 base::MessageLoopForIO::current()->PostTask(
388 base::Bind(&ChannelWin::OnIOCompleted
,
389 weak_factory_
.GetWeakPtr(),
390 &input_state_
.context
,
395 if (!waiting_connect_
)
396 ProcessOutgoingMessages(NULL
, 0);
400 bool ChannelWin::ProcessConnection() {
401 DCHECK(thread_check_
->CalledOnValidThread());
402 if (input_state_
.is_pending
)
403 input_state_
.is_pending
= false;
405 // Do we have a client connected to our pipe?
406 if (!pipe_
.IsValid())
409 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
410 DWORD err
= GetLastError();
412 // Uhm, the API documentation says that this function should never
413 // return success when used in overlapped mode.
419 case ERROR_IO_PENDING
:
420 input_state_
.is_pending
= true;
422 case ERROR_PIPE_CONNECTED
:
423 waiting_connect_
= false;
426 // The pipe is being closed.
436 bool ChannelWin::ProcessOutgoingMessages(
437 base::MessageLoopForIO::IOContext
* context
,
438 DWORD bytes_written
) {
439 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
441 DCHECK(thread_check_
->CalledOnValidThread());
443 if (output_state_
.is_pending
) {
445 output_state_
.is_pending
= false;
446 if (!context
|| bytes_written
== 0) {
447 DWORD err
= GetLastError();
448 LOG(ERROR
) << "pipe error: " << err
;
452 CHECK(!output_queue_
.empty());
453 Message
* m
= output_queue_
.front();
458 if (output_queue_
.empty())
461 if (!pipe_
.IsValid())
465 Message
* m
= output_queue_
.front();
466 DCHECK(m
->size() <= INT_MAX
);
467 BOOL ok
= WriteFile(pipe_
.Get(),
469 static_cast<uint32
>(m
->size()),
471 &output_state_
.context
.overlapped
);
473 DWORD write_error
= GetLastError();
474 if (write_error
== ERROR_IO_PENDING
) {
475 output_state_
.is_pending
= true;
477 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
478 << " with type " << m
->type();
482 LOG(ERROR
) << "pipe error: " << write_error
;
486 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
487 << " with type " << m
->type();
489 output_state_
.is_pending
= true;
493 void ChannelWin::OnIOCompleted(
494 base::MessageLoopForIO::IOContext
* context
,
495 DWORD bytes_transfered
,
498 DCHECK(thread_check_
->CalledOnValidThread());
499 if (context
== &input_state_
.context
) {
500 if (waiting_connect_
) {
501 if (!ProcessConnection())
503 // We may have some messages queued up to send...
504 if (!output_queue_
.empty() && !output_state_
.is_pending
)
505 ProcessOutgoingMessages(NULL
, 0);
506 if (input_state_
.is_pending
)
508 // else, fall-through and look for incoming messages...
511 // We don't support recursion through OnMessageReceived yet!
512 DCHECK(!processing_incoming_
);
513 base::AutoReset
<bool> auto_reset_processing_incoming(
514 &processing_incoming_
, true);
516 // Process the new data.
517 if (input_state_
.is_pending
) {
518 // This is the normal case for everything except the initialization step.
519 input_state_
.is_pending
= false;
520 if (!bytes_transfered
) {
522 } else if (pipe_
.IsValid()) {
523 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
526 DCHECK(!bytes_transfered
);
529 // Request more data.
531 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
533 DCHECK(context
== &output_state_
.context
);
534 CHECK(output_state_
.is_pending
);
535 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
537 if (!ok
&& pipe_
.IsValid()) {
538 // We don't want to re-enter Close().
540 listener()->OnChannelError();
544 //------------------------------------------------------------------------------
548 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
551 AttachmentBroker
* broker
) {
552 return scoped_ptr
<Channel
>(
553 new ChannelWin(channel_handle
, mode
, listener
, broker
));
557 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
558 return ChannelWin::IsNamedServerInitialized(channel_id
);
562 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
563 // Windows pipes can be enumerated by low-privileged processes. So, we
564 // append a strong random value after the \ character. This value is not
565 // included in the pipe name, but sent as part of the client hello, to
566 // hijacking the pipe name to spoof the client.
568 std::string id
= prefix
;
573 do { // Guarantee we get a non-zero value.
574 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
575 } while (secret
== 0);
577 id
.append(GenerateUniqueRandomChannelID());
578 return id
.append(base::StringPrintf("\\%d", secret
));