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 bool ChannelWin::DidEmptyInputBuffers() {
247 // We don't need to do anything here.
252 const base::string16
ChannelWin::PipeName(
253 const std::string
& channel_id
, int32
* secret
) {
254 std::string
name("\\\\.\\pipe\\chrome.");
256 // Prevent the shared secret from ending up in the pipe name.
257 size_t index
= channel_id
.find_first_of('\\');
258 if (index
!= std::string::npos
) {
259 if (secret
) // Retrieve the secret if asked for.
260 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
261 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
264 // This case is here to support predictable named pipes in tests.
267 return base::ASCIIToUTF16(name
.append(channel_id
));
270 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
272 DCHECK(!pipe_
.IsValid());
273 base::string16 pipe_name
;
274 // If we already have a valid pipe for channel just copy it.
275 if (channel_handle
.pipe
.handle
) {
276 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
277 // favor of two independent entities (name/file), or it should be a move-
278 // only type with a base::File member. In any case, this code should not
279 // call DuplicateHandle.
280 DCHECK(channel_handle
.name
.empty());
281 pipe_name
= L
"Not Available"; // Just used for LOG
282 // Check that the given pipe confirms to the specified mode. We can
283 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
284 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
286 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
287 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
288 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
289 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
290 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
294 if (!DuplicateHandle(GetCurrentProcess(),
295 channel_handle
.pipe
.handle
,
300 DUPLICATE_SAME_ACCESS
)) {
301 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
304 pipe_
.Set(local_handle
);
305 } else if (mode
& MODE_SERVER_FLAG
) {
306 DCHECK(!channel_handle
.pipe
.handle
);
307 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
308 FILE_FLAG_FIRST_PIPE_INSTANCE
;
309 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
310 validate_client_
= !!client_secret_
;
311 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
313 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
315 Channel::kReadBufferSize
,
316 Channel::kReadBufferSize
,
319 } else if (mode
& MODE_CLIENT_FLAG
) {
320 DCHECK(!channel_handle
.pipe
.handle
);
321 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
322 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
323 GENERIC_READ
| GENERIC_WRITE
,
327 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
328 FILE_FLAG_OVERLAPPED
,
334 if (!pipe_
.IsValid()) {
335 // If this process is being closed, the pipe may be gone already.
336 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
337 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
341 // Create the Hello message to be sent when Connect is called
342 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
344 IPC::Message::PRIORITY_NORMAL
));
346 // Don't send the secret to the untrusted process, and don't send a secret
347 // if the value is zero (for IPC backwards compatability).
348 int32 secret
= validate_client_
? 0 : client_secret_
;
349 if (!m
->WriteInt(GetCurrentProcessId()) ||
350 (secret
&& !m
->WriteUInt32(secret
))) {
355 output_queue_
.push(m
.release());
359 bool ChannelWin::Connect() {
360 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
362 if (!thread_check_
.get())
363 thread_check_
.reset(new base::ThreadChecker());
365 if (!pipe_
.IsValid())
368 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
370 // Check to see if there is a client connected to our pipe...
371 if (waiting_connect_
)
374 if (!input_state_
.is_pending
) {
375 // Complete setup asynchronously. By not setting input_state_.is_pending
376 // to true, we indicate to OnIOCompleted that this is the special
377 // initialization signal.
378 base::MessageLoopForIO::current()->PostTask(
380 base::Bind(&ChannelWin::OnIOCompleted
,
381 weak_factory_
.GetWeakPtr(),
382 &input_state_
.context
,
387 if (!waiting_connect_
)
388 ProcessOutgoingMessages(NULL
, 0);
392 bool ChannelWin::ProcessConnection() {
393 DCHECK(thread_check_
->CalledOnValidThread());
394 if (input_state_
.is_pending
)
395 input_state_
.is_pending
= false;
397 // Do we have a client connected to our pipe?
398 if (!pipe_
.IsValid())
401 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
402 DWORD err
= GetLastError();
404 // Uhm, the API documentation says that this function should never
405 // return success when used in overlapped mode.
411 case ERROR_IO_PENDING
:
412 input_state_
.is_pending
= true;
414 case ERROR_PIPE_CONNECTED
:
415 waiting_connect_
= false;
418 // The pipe is being closed.
428 bool ChannelWin::ProcessOutgoingMessages(
429 base::MessageLoopForIO::IOContext
* context
,
430 DWORD bytes_written
) {
431 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
433 DCHECK(thread_check_
->CalledOnValidThread());
435 if (output_state_
.is_pending
) {
437 output_state_
.is_pending
= false;
438 if (!context
|| bytes_written
== 0) {
439 DWORD err
= GetLastError();
440 LOG(ERROR
) << "pipe error: " << err
;
444 CHECK(!output_queue_
.empty());
445 Message
* m
= output_queue_
.front();
450 if (output_queue_
.empty())
453 if (!pipe_
.IsValid())
457 Message
* m
= output_queue_
.front();
458 DCHECK(m
->size() <= INT_MAX
);
459 BOOL ok
= WriteFile(pipe_
.Get(),
461 static_cast<uint32
>(m
->size()),
463 &output_state_
.context
.overlapped
);
465 DWORD write_error
= GetLastError();
466 if (write_error
== ERROR_IO_PENDING
) {
467 output_state_
.is_pending
= true;
469 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
470 << " with type " << m
->type();
474 LOG(ERROR
) << "pipe error: " << write_error
;
478 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
479 << " with type " << m
->type();
481 output_state_
.is_pending
= true;
485 void ChannelWin::OnIOCompleted(
486 base::MessageLoopForIO::IOContext
* context
,
487 DWORD bytes_transfered
,
490 DCHECK(thread_check_
->CalledOnValidThread());
491 if (context
== &input_state_
.context
) {
492 if (waiting_connect_
) {
493 if (!ProcessConnection())
495 // We may have some messages queued up to send...
496 if (!output_queue_
.empty() && !output_state_
.is_pending
)
497 ProcessOutgoingMessages(NULL
, 0);
498 if (input_state_
.is_pending
)
500 // else, fall-through and look for incoming messages...
503 // We don't support recursion through OnMessageReceived yet!
504 DCHECK(!processing_incoming_
);
505 base::AutoReset
<bool> auto_reset_processing_incoming(
506 &processing_incoming_
, true);
508 // Process the new data.
509 if (input_state_
.is_pending
) {
510 // This is the normal case for everything except the initialization step.
511 input_state_
.is_pending
= false;
512 if (!bytes_transfered
) {
514 } else if (pipe_
.IsValid()) {
515 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
518 DCHECK(!bytes_transfered
);
521 // Request more data.
523 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
525 DCHECK(context
== &output_state_
.context
);
526 CHECK(output_state_
.is_pending
);
527 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
529 if (!ok
&& pipe_
.IsValid()) {
530 // We don't want to re-enter Close().
532 listener()->OnChannelError();
536 //------------------------------------------------------------------------------
540 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
543 AttachmentBroker
* broker
) {
544 return scoped_ptr
<Channel
>(
545 new ChannelWin(channel_handle
, mode
, listener
, broker
));
549 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
550 return ChannelWin::IsNamedServerInitialized(channel_id
);
554 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
555 // Windows pipes can be enumerated by low-privileged processes. So, we
556 // append a strong random value after the \ character. This value is not
557 // included in the pipe name, but sent as part of the client hello, to
558 // hijacking the pipe name to spoof the client.
560 std::string id
= prefix
;
565 do { // Guarantee we get a non-zero value.
566 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
567 } while (secret
== 0);
569 id
.append(GenerateUniqueRandomChannelID());
570 return id
.append(base::StringPrintf("\\%d", secret
));