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/threading/non_thread_safe.h"
14 #include "base/utf_string_conversions.h"
15 #include "base/win/scoped_handle.h"
16 #include "ipc/ipc_logging.h"
17 #include "ipc/ipc_message_utils.h"
21 Channel::ChannelImpl::State::State(ChannelImpl
* channel
) : is_pending(false) {
22 memset(&context
.overlapped
, 0, sizeof(context
.overlapped
));
23 context
.handler
= channel
;
26 Channel::ChannelImpl::State::~State() {
27 COMPILE_ASSERT(!offsetof(Channel::ChannelImpl::State
, context
),
28 starts_with_io_context
);
31 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle
&channel_handle
,
32 Mode mode
, Listener
* listener
)
33 : ALLOW_THIS_IN_INITIALIZER_LIST(input_state_(this)),
34 ALLOW_THIS_IN_INITIALIZER_LIST(output_state_(this)),
35 pipe_(INVALID_HANDLE_VALUE
),
37 waiting_connect_(mode
& MODE_SERVER_FLAG
),
38 processing_incoming_(false),
39 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
40 CreatePipe(channel_handle
, mode
);
43 Channel::ChannelImpl::~ChannelImpl() {
47 void Channel::ChannelImpl::Close() {
48 if (thread_check_
.get()) {
49 DCHECK(thread_check_
->CalledOnValidThread());
52 if (input_state_
.is_pending
|| output_state_
.is_pending
)
55 // Closing the handle at this point prevents us from issuing more requests
56 // form OnIOCompleted().
57 if (pipe_
!= INVALID_HANDLE_VALUE
) {
59 pipe_
= INVALID_HANDLE_VALUE
;
62 // Make sure all IO has completed.
63 base::Time start
= base::Time::Now();
64 while (input_state_
.is_pending
|| output_state_
.is_pending
) {
65 MessageLoopForIO::current()->WaitForIOCompletion(INFINITE
, this);
68 while (!output_queue_
.empty()) {
69 Message
* m
= output_queue_
.front();
75 bool Channel::ChannelImpl::Send(Message
* message
) {
76 DCHECK(thread_check_
->CalledOnValidThread());
77 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
78 << " with type " << message
->type()
79 << " (" << output_queue_
.size() << " in queue)";
81 #ifdef IPC_MESSAGE_LOG_ENABLED
82 Logging::GetInstance()->OnSendMessage(message
, "");
85 output_queue_
.push(message
);
86 // ensure waiting to write
87 if (!waiting_connect_
) {
88 if (!output_state_
.is_pending
) {
89 if (!ProcessOutgoingMessages(NULL
, 0))
98 bool Channel::ChannelImpl::IsNamedServerInitialized(
99 const std::string
& channel_id
) {
100 if (WaitNamedPipe(PipeName(channel_id
).c_str(), 1))
102 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
104 return GetLastError() == ERROR_SEM_TIMEOUT
;
108 const std::wstring
Channel::ChannelImpl::PipeName(
109 const std::string
& channel_id
) {
110 std::string
name("\\\\.\\pipe\\chrome.");
111 return ASCIIToWide(name
.append(channel_id
));
114 bool Channel::ChannelImpl::CreatePipe(const IPC::ChannelHandle
&channel_handle
,
116 DCHECK_EQ(INVALID_HANDLE_VALUE
, pipe_
);
118 // If we already have a valid pipe for channel just copy it.
119 if (channel_handle
.pipe
.handle
) {
120 DCHECK(channel_handle
.name
.empty());
121 pipe_name
= L
"Not Available"; // Just used for LOG
122 // Check that the given pipe confirms to the specified mode. We can
123 // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the
124 // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0.
126 GetNamedPipeInfo(channel_handle
.pipe
.handle
, &flags
, NULL
, NULL
, NULL
);
127 DCHECK(!(flags
& PIPE_TYPE_MESSAGE
));
128 if (((mode
& MODE_SERVER_FLAG
) && !(flags
& PIPE_SERVER_END
)) ||
129 ((mode
& MODE_CLIENT_FLAG
) && (flags
& PIPE_SERVER_END
))) {
130 LOG(WARNING
) << "Inconsistent open mode. Mode :" << mode
;
133 if (!DuplicateHandle(GetCurrentProcess(),
134 channel_handle
.pipe
.handle
,
139 DUPLICATE_SAME_ACCESS
)) {
140 LOG(WARNING
) << "DuplicateHandle failed. Error :" << GetLastError();
143 } else if (mode
& MODE_SERVER_FLAG
) {
144 DCHECK(!channel_handle
.pipe
.handle
);
145 const DWORD open_mode
= PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
|
146 FILE_FLAG_FIRST_PIPE_INSTANCE
;
147 pipe_name
= PipeName(channel_handle
.name
);
148 pipe_
= CreateNamedPipeW(pipe_name
.c_str(),
150 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
,
152 Channel::kReadBufferSize
,
153 Channel::kReadBufferSize
,
156 } else if (mode
& MODE_CLIENT_FLAG
) {
157 DCHECK(!channel_handle
.pipe
.handle
);
158 pipe_name
= PipeName(channel_handle
.name
);
159 pipe_
= CreateFileW(pipe_name
.c_str(),
160 GENERIC_READ
| GENERIC_WRITE
,
164 SECURITY_SQOS_PRESENT
| SECURITY_IDENTIFICATION
|
165 FILE_FLAG_OVERLAPPED
,
171 if (pipe_
== INVALID_HANDLE_VALUE
) {
172 // If this process is being closed, the pipe may be gone already.
173 LOG(WARNING
) << "Unable to create pipe \"" << pipe_name
<<
174 "\" in " << (mode
== 0 ? "server" : "client")
175 << " mode. Error :" << GetLastError();
179 // Create the Hello message to be sent when Connect is called
180 scoped_ptr
<Message
> m(new Message(MSG_ROUTING_NONE
,
182 IPC::Message::PRIORITY_NORMAL
));
183 if (!m
->WriteInt(GetCurrentProcessId())) {
185 pipe_
= INVALID_HANDLE_VALUE
;
189 output_queue_
.push(m
.release());
193 bool Channel::ChannelImpl::Connect() {
194 DLOG_IF(WARNING
, thread_check_
.get()) << "Connect called more than once";
196 if (!thread_check_
.get())
197 thread_check_
.reset(new base::NonThreadSafe());
199 if (pipe_
== INVALID_HANDLE_VALUE
)
202 MessageLoopForIO::current()->RegisterIOHandler(pipe_
, this);
204 // Check to see if there is a client connected to our pipe...
205 if (waiting_connect_
)
208 if (!input_state_
.is_pending
) {
209 // Complete setup asynchronously. By not setting input_state_.is_pending
210 // to true, we indicate to OnIOCompleted that this is the special
211 // initialization signal.
212 MessageLoopForIO::current()->PostTask(
213 FROM_HERE
, base::Bind(&Channel::ChannelImpl::OnIOCompleted
,
214 weak_factory_
.GetWeakPtr(), &input_state_
.context
,
218 if (!waiting_connect_
)
219 ProcessOutgoingMessages(NULL
, 0);
223 bool Channel::ChannelImpl::ProcessConnection() {
224 DCHECK(thread_check_
->CalledOnValidThread());
225 if (input_state_
.is_pending
)
226 input_state_
.is_pending
= false;
228 // Do we have a client connected to our pipe?
229 if (INVALID_HANDLE_VALUE
== pipe_
)
232 BOOL ok
= ConnectNamedPipe(pipe_
, &input_state_
.context
.overlapped
);
234 DWORD err
= GetLastError();
236 // Uhm, the API documentation says that this function should never
237 // return success when used in overlapped mode.
243 case ERROR_IO_PENDING
:
244 input_state_
.is_pending
= true;
246 case ERROR_PIPE_CONNECTED
:
247 waiting_connect_
= false;
250 // The pipe is being closed.
260 bool Channel::ChannelImpl::ProcessIncomingMessages(
261 MessageLoopForIO::IOContext
* context
,
263 DCHECK(thread_check_
->CalledOnValidThread());
264 if (input_state_
.is_pending
) {
265 input_state_
.is_pending
= false;
268 if (!context
|| !bytes_read
)
271 // This happens at channel initialization.
272 DCHECK(!bytes_read
&& context
== &input_state_
.context
);
276 if (bytes_read
== 0) {
277 if (INVALID_HANDLE_VALUE
== pipe_
)
281 BOOL ok
= ReadFile(pipe_
,
283 Channel::kReadBufferSize
,
285 &input_state_
.context
.overlapped
);
287 DWORD err
= GetLastError();
288 if (err
== ERROR_IO_PENDING
) {
289 input_state_
.is_pending
= true;
292 LOG(ERROR
) << "pipe error: " << err
;
295 input_state_
.is_pending
= true;
300 // Process messages from input buffer.
303 if (input_overflow_buf_
.empty()) {
305 end
= p
+ bytes_read
;
307 if (input_overflow_buf_
.size() > (kMaximumMessageSize
- bytes_read
)) {
308 input_overflow_buf_
.clear();
309 LOG(ERROR
) << "IPC message is too big";
312 input_overflow_buf_
.append(input_buf_
, bytes_read
);
313 p
= input_overflow_buf_
.data();
314 end
= p
+ input_overflow_buf_
.size();
318 const char* message_tail
= Message::FindNext(p
, end
);
320 int len
= static_cast<int>(message_tail
- p
);
321 const Message
m(p
, len
);
322 DVLOG(2) << "received message on channel @" << this
323 << " with type " << m
.type();
324 if (m
.routing_id() == MSG_ROUTING_NONE
&&
325 m
.type() == HELLO_MESSAGE_TYPE
) {
326 // The Hello message contains only the process id.
327 listener_
->OnChannelConnected(MessageIterator(m
).NextInt());
329 listener_
->OnMessageReceived(m
);
333 // Last message is partial.
337 input_overflow_buf_
.assign(p
, end
- p
);
339 bytes_read
= 0; // Get more data.
345 bool Channel::ChannelImpl::ProcessOutgoingMessages(
346 MessageLoopForIO::IOContext
* context
,
347 DWORD bytes_written
) {
348 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
350 DCHECK(thread_check_
->CalledOnValidThread());
352 if (output_state_
.is_pending
) {
354 output_state_
.is_pending
= false;
355 if (!context
|| bytes_written
== 0) {
356 DWORD err
= GetLastError();
357 LOG(ERROR
) << "pipe error: " << err
;
361 DCHECK(!output_queue_
.empty());
362 Message
* m
= output_queue_
.front();
367 if (output_queue_
.empty())
370 if (INVALID_HANDLE_VALUE
== pipe_
)
374 Message
* m
= output_queue_
.front();
375 DCHECK(m
->size() <= INT_MAX
);
376 BOOL ok
= WriteFile(pipe_
,
378 static_cast<int>(m
->size()),
380 &output_state_
.context
.overlapped
);
382 DWORD err
= GetLastError();
383 if (err
== ERROR_IO_PENDING
) {
384 output_state_
.is_pending
= true;
386 DVLOG(2) << "sent pending message @" << m
<< " on channel @" << this
387 << " with type " << m
->type();
391 LOG(ERROR
) << "pipe error: " << err
;
395 DVLOG(2) << "sent message @" << m
<< " on channel @" << this
396 << " with type " << m
->type();
398 output_state_
.is_pending
= true;
402 void Channel::ChannelImpl::OnIOCompleted(MessageLoopForIO::IOContext
* context
,
403 DWORD bytes_transfered
, DWORD error
) {
405 DCHECK(thread_check_
->CalledOnValidThread());
406 if (context
== &input_state_
.context
) {
407 if (waiting_connect_
) {
408 if (!ProcessConnection())
410 // We may have some messages queued up to send...
411 if (!output_queue_
.empty() && !output_state_
.is_pending
)
412 ProcessOutgoingMessages(NULL
, 0);
413 if (input_state_
.is_pending
)
415 // else, fall-through and look for incoming messages...
417 // we don't support recursion through OnMessageReceived yet!
418 DCHECK(!processing_incoming_
);
419 AutoReset
<bool> auto_reset_processing_incoming(&processing_incoming_
, true);
420 ok
= ProcessIncomingMessages(context
, bytes_transfered
);
422 DCHECK(context
== &output_state_
.context
);
423 ok
= ProcessOutgoingMessages(context
, bytes_transfered
);
425 if (!ok
&& INVALID_HANDLE_VALUE
!= pipe_
) {
426 // We don't want to re-enter Close().
428 listener_
->OnChannelError();
432 //------------------------------------------------------------------------------
433 // Channel's methods simply call through to ChannelImpl.
434 Channel::Channel(const IPC::ChannelHandle
&channel_handle
, Mode mode
,
436 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
439 Channel::~Channel() {
440 delete channel_impl_
;
443 bool Channel::Connect() {
444 return channel_impl_
->Connect();
447 void Channel::Close() {
448 channel_impl_
->Close();
451 void Channel::set_listener(Listener
* listener
) {
452 channel_impl_
->set_listener(listener
);
455 bool Channel::Send(Message
* message
) {
456 return channel_impl_
->Send(message
);
460 bool Channel::IsNamedServerInitialized(const std::string
& channel_id
) {
461 return ChannelImpl::IsNamedServerInitialized(channel_id
);