Only send cookie notifications when extensions are enabled
[chromium-blink-merge.git] / ipc / ipc_channel_win.cc
bloba01a272feba8d7c7b8cb157aab83208d1159a263
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"
7 #include <windows.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"
25 namespace IPC {
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"
35 "member.");
38 ChannelWin::ChannelWin(const IPC::ChannelHandle& channel_handle,
39 Mode mode,
40 Listener* listener,
41 AttachmentBroker* broker)
42 : ChannelReader(listener),
43 input_state_(this),
44 output_state_(this),
45 peer_pid_(base::kNullProcessId),
46 waiting_connect_(mode & MODE_SERVER_FLAG),
47 processing_incoming_(false),
48 validate_client_(false),
49 client_secret_(0),
50 broker_(broker),
51 weak_factory_(this) {
52 CreatePipe(channel_handle, mode);
55 ChannelWin::~ChannelWin() {
56 Close();
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().
68 if (pipe_.IsValid())
69 pipe_.Close();
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();
78 output_queue_.pop();
79 delete m;
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);
91 return true;
94 if (message->HasBrokerableAttachments() &&
95 peer_pid_ == base::kNullProcessId) {
96 prelim_queue_.push(message);
97 return true;
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()) {
108 DCHECK(broker_);
109 DCHECK(peer_pid_ != base::kNullProcessId);
110 for (const BrokerableAttachment* attachment :
111 message->attachment_set()->PeekBrokerableAttachments()) {
112 if (!broker_->SendAttachmentToProcess(attachment, peer_pid_)) {
113 delete message;
114 return false;
119 #ifdef IPC_MESSAGE_LOG_ENABLED
120 Logging::GetInstance()->OnSendMessage(message, "");
121 #endif
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))
131 return false;
135 return true;
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);
149 prelim_queue.pop();
153 AttachmentBroker* ChannelWin::GetAttachmentBroker() {
154 return broker_;
157 base::ProcessId ChannelWin::GetPeerPID() const {
158 return peer_pid_;
161 base::ProcessId ChannelWin::GetSelfPID() const {
162 return GetCurrentProcessId();
165 // static
166 bool ChannelWin::IsNamedServerInitialized(
167 const std::string& channel_id) {
168 if (WaitNamedPipe(PipeName(channel_id, NULL).c_str(), 1))
169 return true;
170 // If ERROR_SEM_TIMEOUT occurred, the pipe exists but is handling another
171 // connection.
172 return GetLastError() == ERROR_SEM_TIMEOUT;
175 ChannelWin::ReadState ChannelWin::ReadData(
176 char* buffer,
177 int buffer_len,
178 int* /* bytes_read */) {
179 if (!pipe_.IsValid())
180 return READ_FAILED;
182 DWORD bytes_read = 0;
183 BOOL ok = ReadFile(pipe_.Get(), buffer, buffer_len,
184 &bytes_read, &input_state_.context.overlapped);
185 if (!ok) {
186 DWORD err = GetLastError();
187 if (err == ERROR_IO_PENDING) {
188 input_state_.is_pending = true;
189 return READ_PENDING;
191 LOG(ERROR) << "pipe error: " << err;
192 return READ_FAILED;
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;
204 return READ_PENDING;
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);
211 return true;
214 bool ChannelWin::GetNonBrokeredAttachments(Message* msg) {
215 return true;
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);
222 int32 claimed_pid;
223 bool failed = !it.ReadInt(&claimed_pid);
225 if (!failed && validate_client_) {
226 int32 secret;
227 failed = it.ReadInt(&secret) ? (secret != client_secret_) : true;
230 if (failed) {
231 NOTREACHED();
232 Close();
233 listener()->OnChannelError();
234 return;
237 peer_pid_ = claimed_pid;
238 // Validation completed.
239 validate_client_ = false;
241 FlushPrelimQueue();
243 listener()->OnChannelConnected(claimed_pid);
246 bool ChannelWin::DidEmptyInputBuffers() {
247 // We don't need to do anything here.
248 return true;
251 // static
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.
265 if (secret)
266 *secret = 0;
267 return base::ASCIIToUTF16(name.append(channel_id));
270 bool ChannelWin::CreatePipe(const IPC::ChannelHandle &channel_handle,
271 Mode mode) {
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.
285 DWORD flags = 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;
291 return false;
293 HANDLE local_handle;
294 if (!DuplicateHandle(GetCurrentProcess(),
295 channel_handle.pipe.handle,
296 GetCurrentProcess(),
297 &local_handle,
299 FALSE,
300 DUPLICATE_SAME_ACCESS)) {
301 LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError();
302 return false;
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(),
312 open_mode,
313 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
315 Channel::kReadBufferSize,
316 Channel::kReadBufferSize,
317 5000,
318 NULL));
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,
325 NULL,
326 OPEN_EXISTING,
327 SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS |
328 FILE_FLAG_OVERLAPPED,
329 NULL));
330 } else {
331 NOTREACHED();
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";
338 return false;
341 // Create the Hello message to be sent when Connect is called
342 scoped_ptr<Message> m(new Message(MSG_ROUTING_NONE,
343 HELLO_MESSAGE_TYPE,
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))) {
351 pipe_.Close();
352 return false;
355 output_queue_.push(m.release());
356 return true;
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())
366 return false;
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_)
372 ProcessConnection();
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(
379 FROM_HERE,
380 base::Bind(&ChannelWin::OnIOCompleted,
381 weak_factory_.GetWeakPtr(),
382 &input_state_.context,
384 0));
387 if (!waiting_connect_)
388 ProcessOutgoingMessages(NULL, 0);
389 return true;
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())
399 return false;
401 BOOL ok = ConnectNamedPipe(pipe_.Get(), &input_state_.context.overlapped);
402 DWORD err = GetLastError();
403 if (ok) {
404 // Uhm, the API documentation says that this function should never
405 // return success when used in overlapped mode.
406 NOTREACHED();
407 return false;
410 switch (err) {
411 case ERROR_IO_PENDING:
412 input_state_.is_pending = true;
413 break;
414 case ERROR_PIPE_CONNECTED:
415 waiting_connect_ = false;
416 break;
417 case ERROR_NO_DATA:
418 // The pipe is being closed.
419 return false;
420 default:
421 NOTREACHED();
422 return false;
425 return true;
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
432 // no connection?
433 DCHECK(thread_check_->CalledOnValidThread());
435 if (output_state_.is_pending) {
436 DCHECK(context);
437 output_state_.is_pending = false;
438 if (!context || bytes_written == 0) {
439 DWORD err = GetLastError();
440 LOG(ERROR) << "pipe error: " << err;
441 return false;
443 // Message was sent.
444 CHECK(!output_queue_.empty());
445 Message* m = output_queue_.front();
446 output_queue_.pop();
447 delete m;
450 if (output_queue_.empty())
451 return true;
453 if (!pipe_.IsValid())
454 return false;
456 // Write to pipe...
457 Message* m = output_queue_.front();
458 DCHECK(m->size() <= INT_MAX);
459 BOOL ok = WriteFile(pipe_.Get(),
460 m->data(),
461 static_cast<uint32>(m->size()),
462 NULL,
463 &output_state_.context.overlapped);
464 if (!ok) {
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();
472 return true;
474 LOG(ERROR) << "pipe error: " << write_error;
475 return false;
478 DVLOG(2) << "sent message @" << m << " on channel @" << this
479 << " with type " << m->type();
481 output_state_.is_pending = true;
482 return true;
485 void ChannelWin::OnIOCompleted(
486 base::MessageLoopForIO::IOContext* context,
487 DWORD bytes_transfered,
488 DWORD error) {
489 bool ok = true;
490 DCHECK(thread_check_->CalledOnValidThread());
491 if (context == &input_state_.context) {
492 if (waiting_connect_) {
493 if (!ProcessConnection())
494 return;
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)
499 return;
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) {
513 ok = false;
514 } else if (pipe_.IsValid()) {
515 ok = (AsyncReadComplete(bytes_transfered) != DISPATCH_ERROR);
517 } else {
518 DCHECK(!bytes_transfered);
521 // Request more data.
522 if (ok)
523 ok = (ProcessIncomingMessages() != DISPATCH_ERROR);
524 } else {
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().
531 Close();
532 listener()->OnChannelError();
536 //------------------------------------------------------------------------------
537 // Channel's methods
539 // static
540 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
541 Mode mode,
542 Listener* listener,
543 AttachmentBroker* broker) {
544 return scoped_ptr<Channel>(
545 new ChannelWin(channel_handle, mode, listener, broker));
548 // static
549 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
550 return ChannelWin::IsNamedServerInitialized(channel_id);
553 // static
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;
561 if (!id.empty())
562 id.append(".");
564 int secret;
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));
573 } // namespace IPC