1// Copyright (c) 2011 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.
4
5#include "content/browser/renderer_host/clipboard_message_filter.h"
6
7#import <Cocoa/Cocoa.h>
8
9#include "base/basictypes.h"
10#include "base/bind.h"
11#include "base/bind_helpers.h"
12#include "base/mac/scoped_nsobject.h"
13#include "base/strings/sys_string_conversions.h"
14#include "content/public/browser/browser_thread.h"
15#import "ui/base/cocoa/find_pasteboard.h"
16
17namespace content {
18namespace {
19
20// The number of utf16 code units that will be written to the find pasteboard,
21// longer texts are silently ignored. This is to prevent that a compromised
22// renderer can write unlimited amounts of data into the find pasteboard.
23static const size_t kMaxFindPboardStringLength = 4096;
24
25class WriteFindPboardWrapper {
26 public:
27  explicit WriteFindPboardWrapper(NSString* text)
28      : text_([text retain]) {}
29
30  void Run() {
31    [[FindPasteboard sharedInstance] setFindText:text_];
32  }
33
34 private:
35  base::scoped_nsobject<NSString> text_;
36
37  DISALLOW_COPY_AND_ASSIGN(WriteFindPboardWrapper);
38};
39
40}  // namespace
41
42// Called on the IO thread.
43void ClipboardMessageFilter::OnFindPboardWriteString(
44    const base::string16& text) {
45  if (text.length() <= kMaxFindPboardStringLength) {
46    NSString* nsText = base::SysUTF16ToNSString(text);
47    if (nsText) {
48      // FindPasteboard must be used on the UI thread.
49      BrowserThread::PostTask(
50          BrowserThread::UI, FROM_HERE, base::Bind(
51              &WriteFindPboardWrapper::Run,
52              base::Owned(new WriteFindPboardWrapper(nsText))));
53    }
54  }
55}
56
57}  // namespace content
58