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() {
61 void ChannelWin::Close() {
62 if (thread_check_
.get())
63 DCHECK(thread_check_
->CalledOnValidThread());
65 if (input_state_
.is_pending
|| output_state_
.is_pending
)
66 CancelIo(pipe_
.Get());
68 // Closing the handle at this point prevents us from issuing more requests
69 // form OnIOCompleted().
73 // Make sure all IO has completed.
74 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
75 base::MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
78 while (!output_queue_
.empty()) {
79 OutputElement
* element
= output_queue_
.front();
85 bool ChannelWin::Send(Message
* message
) {
86 DCHECK(thread_check_
->CalledOnValidThread());
87 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
88 << " with type " << message
->type()
89 << " (" << output_queue_
.size() << " in queue)";
91 if (!prelim_queue_
.empty()) {
92 prelim_queue_
.push(message
);
96 if (message
->HasBrokerableAttachments() &&
97 peer_pid_
== base::kNullProcessId
) {
98 prelim_queue_
.push(message
);
102 return ProcessMessageForDelivery(message
);
105 bool ChannelWin::ProcessMessageForDelivery(Message
* message
) {
106 // Sending a brokerable attachment requires a call to Channel::Send(), so
107 // both Send() and ProcessMessageForDelivery() may be re-entrant. Brokered
108 // attachments must be sent before the Message itself.
109 if (message
->HasBrokerableAttachments()) {
111 DCHECK(peer_pid_
!= base::kNullProcessId
);
112 for (const BrokerableAttachment
* attachment
:
113 message
->attachment_set()->PeekBrokerableAttachments()) {
114 if (!broker_
->SendAttachmentToProcess(attachment
, peer_pid_
)) {
121 #ifdef IPC_MESSAGE_LOG_ENABLED
122 Logging::GetInstance()->OnSendMessage(message
, "");
125 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
126 "ChannelWin::ProcessMessageForDelivery",
128 TRACE_EVENT_FLAG_FLOW_OUT
);
130 // |output_queue_| takes ownership of |message|.
131 OutputElement
* element
= new OutputElement(message
);
132 output_queue_
.push(element
);
134 // TODO(erikchen): Serialize the brokerable attachments and add them to the
135 // output_queue_. http://crbug.com/493414.
137 // ensure waiting to write
138 if (!waiting_connect_
) {
139 if (!output_state_
.is_pending
) {
140 if (!ProcessOutgoingMessages(NULL
, 0))
148 void ChannelWin::FlushPrelimQueue() {
149 DCHECK_NE(peer_pid_
, base::kNullProcessId
);
151 // Due to the possibly re-entrant nature of ProcessMessageForDelivery(), it
152 // is critical that |prelim_queue_| appears empty.
153 std::queue
<Message
*> prelim_queue
;
154 prelim_queue_
.swap(prelim_queue
);
156 while (!prelim_queue
.empty()) {
157 Message
* m
= prelim_queue
.front();
158 ProcessMessageForDelivery(m
);
163 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
167 base::ProcessId
ChannelWin::GetPeerPID() const {
171 base::ProcessId
ChannelWin::GetSelfPID() const {
172 return GetCurrentProcessId();
176 bool ChannelWin::IsNamedServerInitialized(
177 const std::string
& channel_id
) {
178 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
180 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
182 return GetLastError() == ERROR_SEM_TIMEOUT
;
185 ChannelWin::ReadState
ChannelWin::ReadData(
188 int* /* bytes_read */) {
189 if (!pipe_
.IsValid())
192 DWORD bytes_read
= 0;
193 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
194 &bytes_read
, &input_state_
.context
.overlapped
);
196 DWORD err
= GetLastError();
197 if (err
== ERROR_IO_PENDING
) {
198 input_state_
.is_pending
= true;
201 LOG(ERROR
) << "pipe error: " << err
;
205 // We could return READ_SUCCEEDED here. But the way that this code is
206 // structured we instead go back to the message loop. Our completion port
207 // will be signalled even in the "synchronously completed" state.
209 // This allows us to potentially process some outgoing messages and
210 // interleave other work on this thread when we're getting hammered with
211 // input messages. Potentially, this could be tuned to be more efficient
212 // with some testing.
213 input_state_
.is_pending
= true;
217 bool ChannelWin::ShouldDispatchInputMessage(Message
* msg
) {
218 // Make sure we get a hello when client validation is required.
219 if (validate_client_
)
220 return IsHelloMessage(*msg
);
224 bool ChannelWin::GetNonBrokeredAttachments(Message
* msg
) {
228 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
229 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
230 // The hello message contains one parameter containing the PID.
231 base::PickleIterator
it(msg
);
233 bool failed
= !it
.ReadInt(&claimed_pid
);
235 if (!failed
&& validate_client_
) {
237 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
243 listener()->OnChannelError();
247 peer_pid_
= claimed_pid
;
248 // Validation completed.
249 validate_client_
= false;
253 listener()->OnChannelConnected(claimed_pid
);
256 base::ProcessId
ChannelWin::GetSenderPID() {
260 bool ChannelWin::IsAttachmentBrokerEndpoint() {
261 return is_attachment_broker_endpoint();
264 bool ChannelWin::DidEmptyInputBuffers() {
265 // We don't need to do anything here.
270 const base::string16
ChannelWin::PipeName(const std::string
& channel_id
,
272 std::string
name("\\\\.\\pipe\\chrome.");
274 // Prevent the shared secret from ending up in the pipe name.
275 size_t index
= channel_id
.find_first_of('\\');
276 if (index
!= std::string::npos
) {
277 if (secret
) // Retrieve the secret if asked for.
278 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
279 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
282 // This case is here to support predictable named pipes in tests.
285 return base::ASCIIToUTF16(name
.append(channel_id
));
288 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
290 DCHECK(!pipe_
.IsValid());
291 base::string16 pipe_name
;
292 // If we already have a valid pipe for channel just copy it.
293 if (channel_handle
.pipe
.handle
) {
294 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
295 // favor of two independent entities (name/file), or it should be a move-
296 // only type with a base::File member. In any case, this code should not
297 // call DuplicateHandle.
298 DCHECK(channel_handle
.name
.empty());
299 pipe_name
= L
"Not Available"; // Just used for LOG
300 // Check that the given pipe confirms to the specified mode. We can
301 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
302 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
304 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
305 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
306 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
307 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
308 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
312 if (!DuplicateHandle(GetCurrentProcess(),
313 channel_handle
.pipe
.handle
,
318 DUPLICATE_SAME_ACCESS
)) {
319 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
322 pipe_
.Set(local_handle
);
323 } else if (mode
& MODE_SERVER_FLAG
) {
324 DCHECK(!channel_handle
.pipe
.handle
);
325 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
326 FILE_FLAG_FIRST_PIPE_INSTANCE
;
327 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
328 validate_client_
= !!client_secret_
;
329 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
331 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
333 Channel::kReadBufferSize
,
334 Channel::kReadBufferSize
,
337 } else if (mode
& MODE_CLIENT_FLAG
) {
338 DCHECK(!channel_handle
.pipe
.handle
);
339 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
340 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
341 GENERIC_READ
| GENERIC_WRITE
,
345 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
346 FILE_FLAG_OVERLAPPED
,
352 if (!pipe_
.IsValid()) {
353 // If this process is being closed, the pipe may be gone already.
354 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
355 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
359 // Create the Hello message to be sent when Connect is called
360 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
362 IPC::Message::PRIORITY_NORMAL
));
364 // Don't send the secret to the untrusted process, and don't send a secret
365 // if the value is zero (for IPC backwards compatability).
366 int32_t secret
= validate_client_
? 0 : client_secret_
;
367 if (!m
->WriteInt(GetCurrentProcessId()) ||
368 (secret
&& !m
->WriteUInt32(secret
))) {
373 OutputElement
* element
= new OutputElement(m
.release());
374 output_queue_
.push(element
);
378 bool ChannelWin::Connect() {
379 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
381 if (!thread_check_
.get())
382 thread_check_
.reset(new base::ThreadChecker());
384 if (!pipe_
.IsValid())
387 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
389 // Check to see if there is a client connected to our pipe...
390 if (waiting_connect_
)
393 if (!input_state_
.is_pending
) {
394 // Complete setup asynchronously. By not setting input_state_.is_pending
395 // to true, we indicate to OnIOCompleted that this is the special
396 // initialization signal.
397 base::MessageLoopForIO::current()->PostTask(
399 base::Bind(&ChannelWin::OnIOCompleted
,
400 weak_factory_
.GetWeakPtr(),
401 &input_state_
.context
,
406 if (!waiting_connect_
)
407 ProcessOutgoingMessages(NULL
, 0);
411 bool ChannelWin::ProcessConnection() {
412 DCHECK(thread_check_
->CalledOnValidThread());
413 if (input_state_
.is_pending
)
414 input_state_
.is_pending
= false;
416 // Do we have a client connected to our pipe?
417 if (!pipe_
.IsValid())
420 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
421 DWORD err
= GetLastError();
423 // Uhm, the API documentation says that this function should never
424 // return success when used in overlapped mode.
430 case ERROR_IO_PENDING
:
431 input_state_
.is_pending
= true;
433 case ERROR_PIPE_CONNECTED
:
434 waiting_connect_
= false;
437 // The pipe is being closed.
447 bool ChannelWin::ProcessOutgoingMessages(
448 base::MessageLoopForIO::IOContext
* context
,
449 DWORD bytes_written
) {
450 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
452 DCHECK(thread_check_
->CalledOnValidThread());
454 if (output_state_
.is_pending
) {
456 output_state_
.is_pending
= false;
457 if (!context
|| bytes_written
== 0) {
458 DWORD err
= GetLastError();
459 LOG(ERROR
) << "pipe error: " << err
;
463 CHECK(!output_queue_
.empty());
464 OutputElement
* element
= output_queue_
.front();
469 if (output_queue_
.empty())
472 if (!pipe_
.IsValid())
476 OutputElement
* element
= output_queue_
.front();
477 DCHECK(element
->size() <= INT_MAX
);
478 BOOL ok
= WriteFile(pipe_
.Get(),
480 static_cast<uint32_t>(element
->size()),
482 &output_state_
.context
.overlapped
);
484 DWORD write_error
= GetLastError();
485 if (write_error
== ERROR_IO_PENDING
) {
486 output_state_
.is_pending
= true;
488 const Message
* m
= element
->get_message();
490 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
491 << " with type " << m
->type();
496 LOG(ERROR
) << "pipe error: " << write_error
;
500 const Message
* m
= element
->get_message();
502 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
503 << " with type " << m
->type();
506 output_state_
.is_pending
= true;
510 void ChannelWin::OnIOCompleted(
511 base::MessageLoopForIO::IOContext
* context
,
512 DWORD bytes_transfered
,
515 DCHECK(thread_check_
->CalledOnValidThread());
516 if (context
== &input_state_
.context
) {
517 if (waiting_connect_
) {
518 if (!ProcessConnection())
520 // We may have some messages queued up to send...
521 if (!output_queue_
.empty() && !output_state_
.is_pending
)
522 ProcessOutgoingMessages(NULL
, 0);
523 if (input_state_
.is_pending
)
525 // else, fall-through and look for incoming messages...
528 // We don't support recursion through OnMessageReceived yet!
529 DCHECK(!processing_incoming_
);
530 base::AutoReset
<bool> auto_reset_processing_incoming(
531 &processing_incoming_
, true);
533 // Process the new data.
534 if (input_state_
.is_pending
) {
535 // This is the normal case for everything except the initialization step.
536 input_state_
.is_pending
= false;
537 if (!bytes_transfered
) {
539 } else if (pipe_
.IsValid()) {
540 ok
= (AsyncReadComplete(bytes_transfered
) != DISPATCH_ERROR
);
543 DCHECK(!bytes_transfered
);
546 // Request more data.
548 ok
= (ProcessIncomingMessages() != DISPATCH_ERROR
);
550 DCHECK(context
== &output_state_
.context
);
551 CHECK(output_state_
.is_pending
);
552 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
554 if (!ok
&& pipe_
.IsValid()) {
555 // We don't want to re-enter Close().
557 listener()->OnChannelError();
561 //------------------------------------------------------------------------------
565 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
568 AttachmentBroker
* broker
) {
569 return scoped_ptr
<Channel
>(
570 new ChannelWin(channel_handle
, mode
, listener
, broker
));
574 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
575 return ChannelWin::IsNamedServerInitialized(channel_id
);
579 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
580 // Windows pipes can be enumerated by low-privileged processes. So, we
581 // append a strong random value after the \ character. This value is not
582 // included in the pipe name, but sent as part of the client hello, to
583 // hijacking the pipe name to spoof the client.
585 std::string id
= prefix
;
590 do { // Guarantee we get a non-zero value.
591 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
592 } while (secret
== 0);
594 id
.append(GenerateUniqueRandomChannelID());
595 return id
.append(base::StringPrintf("\\%d", secret
));