summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/extensions/miscellaneous_bindings.cc
blob: 35d24bd4ffc3af735bbf6ed5bcb6313834d0a80c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/extensions/miscellaneous_bindings.h"

#include <map>
#include <string>

#include "base/basictypes.h"
#include "base/lazy_instance.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/message_bundle.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/chrome_v8_context.h"
#include "chrome/renderer/extensions/chrome_v8_context_set.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "chrome/renderer/extensions/dispatcher.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h"
#include "v8/include/v8.h"

// Message passing API example (in a content script):
// var extension =
//    new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
// var port = runtime.connect();
// port.postMessage('Can you hear me now?');
// port.onmessage.addListener(function(msg, port) {
//   alert('response=' + msg);
//   port.postMessage('I got your reponse');
// });

using content::RenderThread;

namespace {

struct ExtensionData {
  struct PortData {
    int ref_count;  // how many contexts have a handle to this port
    PortData() : ref_count(0) {}
  };
  std::map<int, PortData> ports;  // port ID -> data
};

static base::LazyInstance<ExtensionData> g_extension_data =
    LAZY_INSTANCE_INITIALIZER;

static bool HasPortData(int port_id) {
  return g_extension_data.Get().ports.find(port_id) !=
      g_extension_data.Get().ports.end();
}

static ExtensionData::PortData& GetPortData(int port_id) {
  return g_extension_data.Get().ports[port_id];
}

static void ClearPortData(int port_id) {
  g_extension_data.Get().ports.erase(port_id);
}

const char kPortClosedError[] = "Attempting to use a disconnected port object";

class ExtensionImpl : public extensions::ChromeV8Extension {
 public:
  explicit ExtensionImpl(extensions::Dispatcher* dispatcher,
                         v8::Handle<v8::Context> context)
      : extensions::ChromeV8Extension(dispatcher, context) {
    RouteStaticFunction("CloseChannel", &CloseChannel);
    RouteStaticFunction("PortAddRef", &PortAddRef);
    RouteStaticFunction("PortRelease", &PortRelease);
    RouteStaticFunction("PostMessage", &PostMessage);
    RouteStaticFunction("BindToGC", &BindToGC);
  }

  virtual ~ExtensionImpl() {}

  // Sends a message along the given channel.
  static v8::Handle<v8::Value> PostMessage(const v8::Arguments& args) {
    ExtensionImpl* self = GetFromArguments<ExtensionImpl>(args);
    content::RenderView* renderview = self->GetRenderView();
    if (!renderview)
      return v8::Undefined();

    if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsString()) {
      int port_id = args[0]->Int32Value();
      if (!HasPortData(port_id)) {
        return v8::ThrowException(v8::Exception::Error(
          v8::String::New(kPortClosedError)));
      }
      std::string message = *v8::String::Utf8Value(args[1]->ToString());
      renderview->Send(new ExtensionHostMsg_PostMessage(
          renderview->GetRoutingID(), port_id, message));
    }
    return v8::Undefined();
  }

  // Forcefully disconnects a port.
  static v8::Handle<v8::Value> CloseChannel(const v8::Arguments& args) {
    if (args.Length() >= 2 && args[0]->IsInt32() && args[1]->IsBoolean()) {
      int port_id = args[0]->Int32Value();
      if (!HasPortData(port_id)) {
        return v8::Undefined();
      }
      // Send via the RenderThread because the RenderView might be closing.
      bool notify_browser = args[1]->BooleanValue();
      if (notify_browser)
        content::RenderThread::Get()->Send(
            new ExtensionHostMsg_CloseChannel(port_id, false));
      ClearPortData(port_id);
    }
    return v8::Undefined();
  }

  // A new port has been created for a context.  This occurs both when script
  // opens a connection, and when a connection is opened to this script.
  static v8::Handle<v8::Value> PortAddRef(const v8::Arguments& args) {
    if (args.Length() >= 1 && args[0]->IsInt32()) {
      int port_id = args[0]->Int32Value();
      ++GetPortData(port_id).ref_count;
    }
    return v8::Undefined();
  }

  // The frame a port lived in has been destroyed.  When there are no more
  // frames with a reference to a given port, we will disconnect it and notify
  // the other end of the channel.
  static v8::Handle<v8::Value> PortRelease(const v8::Arguments& args) {
    if (args.Length() >= 1 && args[0]->IsInt32()) {
      int port_id = args[0]->Int32Value();
      if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
        // Send via the RenderThread because the RenderView might be closing.
        content::RenderThread::Get()->Send(
            new ExtensionHostMsg_CloseChannel(port_id, false));
        ClearPortData(port_id);
      }
    }
    return v8::Undefined();
  }

  struct GCCallbackArgs {
    v8::Persistent<v8::Object> object;
    v8::Persistent<v8::Function> callback;
  };

  static void GCCallback(v8::Isolate* isolate,
                         v8::Persistent<v8::Value> object,
                         void* parameter) {
    v8::HandleScope handle_scope;
    GCCallbackArgs* args = reinterpret_cast<GCCallbackArgs*>(parameter);
    WebKit::WebScopedMicrotaskSuppression suppression;
    args->callback->Call(args->callback->CreationContext()->Global(), 0, NULL);
    args->callback.Dispose(isolate);
    args->object.Dispose(isolate);
    delete args;
  }

  // Binds a callback to be invoked when the given object is garbage collected.
  static v8::Handle<v8::Value> BindToGC(const v8::Arguments& args) {
    if (args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction()) {
      v8::Isolate* isolate = args.GetIsolate();
      GCCallbackArgs* context = new GCCallbackArgs;
      context->callback = v8::Persistent<v8::Function>::New(
          isolate,
          v8::Handle<v8::Function>::Cast(args[1]));
      context->object = v8::Persistent<v8::Object>::New(
          isolate,
          v8::Handle<v8::Object>::Cast(args[0]));
      context->object.MakeWeak(isolate, context, GCCallback);
    } else {
      NOTREACHED();
    }
    return v8::Undefined();
  }
};

}  // namespace

namespace extensions {

ChromeV8Extension* MiscellaneousBindings::Get(
    Dispatcher* dispatcher,
    v8::Handle<v8::Context> context) {
  return new ExtensionImpl(dispatcher, context);
}

// static
void MiscellaneousBindings::DispatchOnConnect(
    const ChromeV8ContextSet::ContextSet& contexts,
    int target_port_id,
    const std::string& channel_name,
    const std::string& tab_json,
    const std::string& source_extension_id,
    const std::string& target_extension_id,
    content::RenderView* restrict_to_render_view) {
  v8::HandleScope handle_scope;

  bool port_created = false;

  for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
       it != contexts.end(); ++it) {
    if (restrict_to_render_view &&
        restrict_to_render_view != (*it)->GetRenderView()) {
      continue;
    }

    std::vector<v8::Handle<v8::Value> > arguments;
    arguments.push_back(v8::Integer::New(target_port_id));
    arguments.push_back(v8::String::New(channel_name.c_str(),
                                        channel_name.size()));
    arguments.push_back(v8::String::New(tab_json.c_str(),
                                        tab_json.size()));
    arguments.push_back(v8::String::New(source_extension_id.c_str(),
                                        source_extension_id.size()));
    arguments.push_back(v8::String::New(target_extension_id.c_str(),
                                        target_extension_id.size()));
    v8::Handle<v8::Value> retval;
    v8::TryCatch try_catch;
    if (!(*it)->CallChromeHiddenMethod("Port.dispatchOnConnect",
                                      arguments.size(), &arguments[0],
                                      &retval)) {
      continue;
    }

    if (try_catch.HasCaught()) {
      LOG(ERROR) << "Exception caught when calling Port.dispatchOnConnect.";
      continue;
    }

    if (retval.IsEmpty()) {
      LOG(ERROR) << "Empty return value from Port.dispatchOnConnect.";
      continue;
    }

    CHECK(retval->IsBoolean());
    if (retval->BooleanValue())
      port_created = true;
  }

  // If we didn't create a port, notify the other end of the channel (treat it
  // as a disconnect).
  if (!port_created) {
    content::RenderThread::Get()->Send(
        new ExtensionHostMsg_CloseChannel(target_port_id, true));
  }
}

// static
void MiscellaneousBindings::DeliverMessage(
    const ChromeV8ContextSet::ContextSet& contexts,
    int target_port_id,
    const std::string& message,
    content::RenderView* restrict_to_render_view) {
  v8::HandleScope handle_scope;

  for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
       it != contexts.end(); ++it) {
    if (restrict_to_render_view &&
        restrict_to_render_view != (*it)->GetRenderView()) {
      continue;
    }

    // Check to see whether the context has this port before bothering to create
    // the message.
    v8::Handle<v8::Value> port_id_handle = v8::Integer::New(target_port_id);
    v8::Handle<v8::Value> has_port;
    v8::TryCatch try_catch;
    if (!(*it)->CallChromeHiddenMethod("Port.hasPort", 1, &port_id_handle,
                                       &has_port)) {
      continue;
    }

    if (try_catch.HasCaught()) {
      LOG(ERROR) << "Exception caught when calling Port.hasPort.";
      continue;
    }

    CHECK(!has_port.IsEmpty());
    if (!has_port->BooleanValue())
      continue;

    std::vector<v8::Handle<v8::Value> > arguments;
    arguments.push_back(v8::String::New(message.c_str(), message.size()));
    arguments.push_back(port_id_handle);
    CHECK((*it)->CallChromeHiddenMethod("Port.dispatchOnMessage",
                                        arguments.size(),
                                        &arguments[0],
                                        NULL));
  }
}

// static
void MiscellaneousBindings::DispatchOnDisconnect(
    const ChromeV8ContextSet::ContextSet& contexts,
    int port_id,
    bool connection_error,
    content::RenderView* restrict_to_render_view) {
  v8::HandleScope handle_scope;

  for (ChromeV8ContextSet::ContextSet::const_iterator it = contexts.begin();
       it != contexts.end(); ++it) {
    if (restrict_to_render_view &&
        restrict_to_render_view != (*it)->GetRenderView()) {
      continue;
    }

    std::vector<v8::Handle<v8::Value> > arguments;
    arguments.push_back(v8::Integer::New(port_id));
    arguments.push_back(v8::Boolean::New(connection_error));
    (*it)->CallChromeHiddenMethod("Port.dispatchOnDisconnect",
                                  arguments.size(), &arguments[0],
                                  NULL);
  }
}

}  // namespace extensions