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_utils.h"
26 ChannelWin::State::State(ChannelWin
* channel
) : is_pending(false) {
27 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
28 context
.handler
= channel
;
31 ChannelWin::State::~State() {
32 static_assert(offsetof(ChannelWin::State
, context
) == 0,
33 "ChannelWin::State should have context as its first data"
37 ChannelWin::ChannelWin(const IPC::ChannelHandle
& channel_handle
,
40 AttachmentBroker
* broker
)
41 : ChannelReader(listener
),
44 peer_pid_(base::kNullProcessId
),
45 waiting_connect_(mode
& MODE_SERVER_FLAG
),
46 processing_incoming_(false),
47 validate_client_(false),
51 CreatePipe(channel_handle
, mode
);
54 ChannelWin::~ChannelWin() {
58 void ChannelWin::Close() {
59 if (thread_check_
.get())
60 DCHECK(thread_check_
->CalledOnValidThread());
62 if (input_state_
.is_pending
|| output_state_
.is_pending
)
63 CancelIo(pipe_
.Get());
65 // Closing the handle at this point prevents us from issuing more requests
66 // form OnIOCompleted().
70 // Make sure all IO has completed.
71 base::Time start
= base::Time::Now();
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(!message
->HasAttachments());
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 #ifdef IPC_MESSAGE_LOG_ENABLED
91 Logging::GetInstance()->OnSendMessage(message
, "");
94 message
->TraceMessageBegin();
95 output_queue_
.push(message
);
96 // ensure waiting to write
97 if (!waiting_connect_
) {
98 if (!output_state_
.is_pending
) {
99 if (!ProcessOutgoingMessages(NULL
, 0))
107 AttachmentBroker
* ChannelWin::GetAttachmentBroker() {
111 base::ProcessId
ChannelWin::GetPeerPID() const {
115 base::ProcessId
ChannelWin::GetSelfPID() const {
116 return GetCurrentProcessId();
120 bool ChannelWin::IsNamedServerInitialized(
121 const std::string
& channel_id
) {
122 if (WaitNamedPipe(PipeName(channel_id
, NULL
).c_str(), 1))
124 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
126 return GetLastError() == ERROR_SEM_TIMEOUT
;
129 ChannelWin::ReadState
ChannelWin::ReadData(
132 int* /* bytes_read */) {
133 if (!pipe_
.IsValid())
136 DWORD bytes_read
= 0;
137 BOOL ok
= ReadFile(pipe_
.Get(), buffer
, buffer_len
,
138 &bytes_read
, &input_state_
.context
.overlapped
);
140 DWORD err
= GetLastError();
141 if (err
== ERROR_IO_PENDING
) {
142 input_state_
.is_pending
= true;
145 LOG(ERROR
) << "pipe error: " << err
;
149 // We could return READ_SUCCEEDED here. But the way that this code is
150 // structured we instead go back to the message loop. Our completion port
151 // will be signalled even in the "synchronously completed" state.
153 // This allows us to potentially process some outgoing messages and
154 // interleave other work on this thread when we're getting hammered with
155 // input messages. Potentially, this could be tuned to be more efficient
156 // with some testing.
157 input_state_
.is_pending
= true;
161 bool ChannelWin::WillDispatchInputMessage(Message
* msg
) {
162 // Make sure we get a hello when client validation is required.
163 if (validate_client_
)
164 return IsHelloMessage(*msg
);
168 void ChannelWin::HandleInternalMessage(const Message
& msg
) {
169 DCHECK_EQ(msg
.type(), static_cast<unsigned>(Channel::HELLO_MESSAGE_TYPE
));
170 // The hello message contains one parameter containing the PID.
171 base::PickleIterator
it(msg
);
173 bool failed
= !it
.ReadInt(&claimed_pid
);
175 if (!failed
&& validate_client_
) {
177 failed
= it
.ReadInt(&secret
) ? (secret
!= client_secret_
) : true;
183 listener()->OnChannelError();
187 peer_pid_
= claimed_pid
;
188 // Validation completed.
189 validate_client_
= false;
190 listener()->OnChannelConnected(claimed_pid
);
193 bool ChannelWin::DidEmptyInputBuffers() {
194 // We don't need to do anything here.
199 const base::string16
ChannelWin::PipeName(
200 const std::string
& channel_id
, int32
* secret
) {
201 std::string
name("\\\\.\\pipe\\chrome.");
203 // Prevent the shared secret from ending up in the pipe name.
204 size_t index
= channel_id
.find_first_of('\\');
205 if (index
!= std::string::npos
) {
206 if (secret
) // Retrieve the secret if asked for.
207 base::StringToInt(channel_id
.substr(index
+ 1), secret
);
208 return base::ASCIIToUTF16(name
.append(channel_id
.substr(0, index
- 1)));
211 // This case is here to support predictable named pipes in tests.
214 return base::ASCIIToUTF16(name
.append(channel_id
));
217 bool ChannelWin::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
219 DCHECK(!pipe_
.IsValid());
220 base::string16 pipe_name
;
221 // If we already have a valid pipe for channel just copy it.
222 if (channel_handle
.pipe
.handle
) {
223 // TODO(rvargas) crbug.com/415294: ChannelHandle should either go away in
224 // favor of two independent entities (name/file), or it should be a move-
225 // only type with a base::File member. In any case, this code should not
226 // call DuplicateHandle.
227 DCHECK(channel_handle
.name
.empty());
228 pipe_name
= L
"Not Available"; // Just used for LOG
229 // Check that the given pipe confirms to the specified mode. We can
230 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
231 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
233 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
234 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
235 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
236 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
237 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
241 if (!DuplicateHandle(GetCurrentProcess(),
242 channel_handle
.pipe
.handle
,
247 DUPLICATE_SAME_ACCESS
)) {
248 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
251 pipe_
.Set(local_handle
);
252 } else if (mode
& MODE_SERVER_FLAG
) {
253 DCHECK(!channel_handle
.pipe
.handle
);
254 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
255 FILE_FLAG_FIRST_PIPE_INSTANCE
;
256 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
257 validate_client_
= !!client_secret_
;
258 pipe_
.Set(CreateNamedPipeW(pipe_name
.c_str(),
260 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
262 Channel::kReadBufferSize
,
263 Channel::kReadBufferSize
,
266 } else if (mode
& MODE_CLIENT_FLAG
) {
267 DCHECK(!channel_handle
.pipe
.handle
);
268 pipe_name
= PipeName(channel_handle
.name
, &client_secret_
);
269 pipe_
.Set(CreateFileW(pipe_name
.c_str(),
270 GENERIC_READ
| GENERIC_WRITE
,
274 SECURITY_SQOS_PRESENT
| SECURITY_ANONYMOUS
|
275 FILE_FLAG_OVERLAPPED
,
281 if (!pipe_
.IsValid()) {
282 // If this process is being closed, the pipe may be gone already.
283 PLOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<< "\" in "
284 << (mode
& MODE_SERVER_FLAG
? "server" : "client") << " mode";
288 // Create the Hello message to be sent when Connect is called
289 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
291 IPC::Message::PRIORITY_NORMAL
));
293 // Don't send the secret to the untrusted process, and don't send a secret
294 // if the value is zero (for IPC backwards compatability).
295 int32 secret
= validate_client_
? 0 : client_secret_
;
296 if (!m
->WriteInt(GetCurrentProcessId()) ||
297 (secret
&& !m
->WriteUInt32(secret
))) {
302 output_queue_
.push(m
.release());
306 bool ChannelWin::Connect() {
307 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
309 if (!thread_check_
.get())
310 thread_check_
.reset(new base::ThreadChecker());
312 if (!pipe_
.IsValid())
315 base::MessageLoopForIO::current()->RegisterIOHandler(pipe_
.Get(), this);
317 // Check to see if there is a client connected to our pipe...
318 if (waiting_connect_
)
321 if (!input_state_
.is_pending
) {
322 // Complete setup asynchronously. By not setting input_state_.is_pending
323 // to true, we indicate to OnIOCompleted that this is the special
324 // initialization signal.
325 base::MessageLoopForIO::current()->PostTask(
327 base::Bind(&ChannelWin::OnIOCompleted
,
328 weak_factory_
.GetWeakPtr(),
329 &input_state_
.context
,
334 if (!waiting_connect_
)
335 ProcessOutgoingMessages(NULL
, 0);
339 bool ChannelWin::ProcessConnection() {
340 DCHECK(thread_check_
->CalledOnValidThread());
341 if (input_state_
.is_pending
)
342 input_state_
.is_pending
= false;
344 // Do we have a client connected to our pipe?
345 if (!pipe_
.IsValid())
348 BOOL ok
= ConnectNamedPipe(pipe_
.Get(), &input_state_
.context
.overlapped
);
349 DWORD err
= GetLastError();
351 // Uhm, the API documentation says that this function should never
352 // return success when used in overlapped mode.
358 case ERROR_IO_PENDING
:
359 input_state_
.is_pending
= true;
361 case ERROR_PIPE_CONNECTED
:
362 waiting_connect_
= false;
365 // The pipe is being closed.
375 bool ChannelWin::ProcessOutgoingMessages(
376 base::MessageLoopForIO::IOContext
* context
,
377 DWORD bytes_written
) {
378 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
380 DCHECK(thread_check_
->CalledOnValidThread());
382 if (output_state_
.is_pending
) {
384 output_state_
.is_pending
= false;
385 if (!context
|| bytes_written
== 0) {
386 DWORD err
= GetLastError();
387 LOG(ERROR
) << "pipe error: " << err
;
391 CHECK(!output_queue_
.empty());
392 Message
* m
= output_queue_
.front();
397 if (output_queue_
.empty())
400 if (!pipe_
.IsValid())
404 Message
* m
= output_queue_
.front();
405 DCHECK(m
->size() <= INT_MAX
);
406 BOOL ok
= WriteFile(pipe_
.Get(),
408 static_cast<uint32
>(m
->size()),
410 &output_state_
.context
.overlapped
);
412 DWORD write_error
= GetLastError();
413 if (write_error
== ERROR_IO_PENDING
) {
414 output_state_
.is_pending
= true;
416 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
417 << " with type " << m
->type();
421 LOG(ERROR
) << "pipe error: " << write_error
;
425 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
426 << " with type " << m
->type();
428 output_state_
.is_pending
= true;
432 void ChannelWin::OnIOCompleted(
433 base::MessageLoopForIO::IOContext
* context
,
434 DWORD bytes_transfered
,
437 DCHECK(thread_check_
->CalledOnValidThread());
438 if (context
== &input_state_
.context
) {
439 if (waiting_connect_
) {
440 if (!ProcessConnection())
442 // We may have some messages queued up to send...
443 if (!output_queue_
.empty() && !output_state_
.is_pending
)
444 ProcessOutgoingMessages(NULL
, 0);
445 if (input_state_
.is_pending
)
447 // else, fall-through and look for incoming messages...
450 // We don't support recursion through OnMessageReceived yet!
451 DCHECK(!processing_incoming_
);
452 base::AutoReset
<bool> auto_reset_processing_incoming(
453 &processing_incoming_
, true);
455 // Process the new data.
456 if (input_state_
.is_pending
) {
457 // This is the normal case for everything except the initialization step.
458 input_state_
.is_pending
= false;
459 if (!bytes_transfered
)
461 else if (pipe_
.IsValid())
462 ok
= AsyncReadComplete(bytes_transfered
);
464 DCHECK(!bytes_transfered
);
467 // Request more data.
469 ok
= ProcessIncomingMessages();
471 DCHECK(context
== &output_state_
.context
);
472 CHECK(output_state_
.is_pending
);
473 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
475 if (!ok
&& pipe_
.IsValid()) {
476 // We don't want to re-enter Close().
478 listener()->OnChannelError();
482 //------------------------------------------------------------------------------
486 scoped_ptr
<Channel
> Channel::Create(const IPC::ChannelHandle
& channel_handle
,
489 AttachmentBroker
* broker
) {
490 return scoped_ptr
<Channel
>(
491 new ChannelWin(channel_handle
, mode
, listener
, broker
));
495 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
496 return ChannelWin::IsNamedServerInitialized(channel_id
);
500 std::string
Channel::GenerateVerifiedChannelID(const std::string
& prefix
) {
501 // Windows pipes can be enumerated by low-privileged processes. So, we
502 // append a strong random value after the \ character. This value is not
503 // included in the pipe name, but sent as part of the client hello, to
504 // hijacking the pipe name to spoof the client.
506 std::string id
= prefix
;
511 do { // Guarantee we get a non-zero value.
512 secret
= base::RandInt(0, std::numeric_limits
<int>::max());
513 } while (secret
== 0);
515 id
.append(GenerateUniqueRandomChannelID());
516 return id
.append(base::StringPrintf("\\%d", secret
));