electron/lib/browser/rpc-server.js

478 lines
15 KiB
JavaScript
Raw Normal View History

2016-03-24 20:34:36 +00:00
'use strict'
const { spawn } = require('child_process')
2016-03-24 20:34:36 +00:00
const electron = require('electron')
2018-09-13 16:10:51 +00:00
const { EventEmitter } = require('events')
const fs = require('fs')
const os = require('os')
const path = require('path')
2016-03-24 20:34:36 +00:00
const v8Util = process.atomBinding('v8_util')
2018-09-13 16:10:51 +00:00
const { ipcMain, isPromise } = electron
const objectsRegistry = require('@electron/internal/browser/objects-registry')
const bufferUtils = require('@electron/internal/common/buffer-utils')
const errorUtils = require('@electron/internal/common/error-utils')
2016-01-12 02:40:23 +00:00
const hasProp = {}.hasOwnProperty
// The internal properties of Function.
const FUNCTION_PROPERTIES = [
2016-03-24 20:34:36 +00:00
'length', 'name', 'arguments', 'caller', 'prototype'
]
// The remote functions in renderer processes.
// id => Function
const rendererFunctions = v8Util.createDoubleIDWeakMap()
// Return the description of object's members:
const getObjectMembers = function (object) {
2016-03-24 20:34:36 +00:00
let names = Object.getOwnPropertyNames(object)
// For Function, we should not override following properties even though they
// are "own" properties.
if (typeof object === 'function') {
names = names.filter((name) => {
2016-03-24 20:34:36 +00:00
return !FUNCTION_PROPERTIES.includes(name)
})
}
// Map properties to descriptors.
return names.map((name) => {
const descriptor = Object.getOwnPropertyDescriptor(object, name)
const member = { name, enumerable: descriptor.enumerable, writable: false }
if (descriptor.get === undefined && typeof object[name] === 'function') {
2016-03-24 20:34:36 +00:00
member.type = 'method'
} else {
2016-03-24 20:34:36 +00:00
if (descriptor.set || descriptor.writable) member.writable = true
member.type = 'get'
}
2016-03-24 20:34:36 +00:00
return member
})
}
// Return the description of object's prototype.
const getObjectPrototype = function (object) {
const proto = Object.getPrototypeOf(object)
2016-03-24 20:34:36 +00:00
if (proto === null || proto === Object.prototype) return null
return {
2016-03-04 23:57:21 +00:00
members: getObjectMembers(proto),
2016-03-24 20:34:36 +00:00
proto: getObjectPrototype(proto)
}
}
2016-01-14 18:35:29 +00:00
// Convert a real value into meta data.
const valueToMeta = function (sender, contextId, value, optimizeSimpleObject = false) {
// Determine the type of value.
const meta = { type: typeof value }
if (meta.type === 'object') {
// Recognize certain types of objects.
if (value === null) {
meta.type = 'value'
} else if (bufferUtils.isBuffer(value)) {
meta.type = 'buffer'
} else if (Array.isArray(value)) {
meta.type = 'array'
} else if (value instanceof Error) {
meta.type = 'error'
} else if (value instanceof Date) {
meta.type = 'date'
2016-05-25 05:38:35 +00:00
} else if (isPromise(value)) {
meta.type = 'promise'
} else if (hasProp.call(value, 'callee') && value.length != null) {
// Treat the arguments object as array.
meta.type = 'array'
} else if (optimizeSimpleObject && v8Util.getHiddenValue(value, 'simple')) {
// Treat simple objects as value.
meta.type = 'value'
}
2016-01-12 02:40:23 +00:00
}
// Fill the meta object according to value's type.
2016-01-12 02:40:23 +00:00
if (meta.type === 'array') {
meta.members = value.map((el) => valueToMeta(sender, contextId, el, optimizeSimpleObject))
2016-01-12 02:40:23 +00:00
} else if (meta.type === 'object' || meta.type === 'function') {
meta.name = value.constructor ? value.constructor.name : ''
2016-01-12 02:40:23 +00:00
2016-01-14 18:44:21 +00:00
// Reference the original value if it's an object, because when it's
// passed to renderer we would assume the renderer keeps a reference of
// it.
meta.id = objectsRegistry.add(sender, contextId, value)
2016-03-24 20:34:36 +00:00
meta.members = getObjectMembers(value)
meta.proto = getObjectPrototype(value)
2016-01-12 02:40:23 +00:00
} else if (meta.type === 'buffer') {
meta.value = bufferUtils.bufferToMeta(value)
2016-01-12 02:40:23 +00:00
} else if (meta.type === 'promise') {
// Add default handler to prevent unhandled rejections in main process
// Instead they should appear in the renderer process
value.then(function () {}, function () {})
meta.then = valueToMeta(sender, contextId, function (onFulfilled, onRejected) {
2016-05-23 22:07:01 +00:00
value.then(onFulfilled, onRejected)
})
2016-01-12 02:40:23 +00:00
} else if (meta.type === 'error') {
2016-03-24 20:34:36 +00:00
meta.members = plainObjectToMeta(value)
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Error.name is not part of own properties.
2016-01-12 02:40:23 +00:00
meta.members.push({
name: 'name',
value: value.name
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
} else if (meta.type === 'date') {
2016-03-24 20:34:36 +00:00
meta.value = value.getTime()
2016-01-12 02:40:23 +00:00
} else {
2016-03-24 20:34:36 +00:00
meta.type = 'value'
meta.value = value
2016-01-12 02:40:23 +00:00
}
2016-03-24 20:34:36 +00:00
return meta
}
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Convert object to meta by value.
const plainObjectToMeta = function (obj) {
2016-03-24 20:34:36 +00:00
return Object.getOwnPropertyNames(obj).map(function (name) {
2016-01-12 02:40:23 +00:00
return {
name: name,
value: obj[name]
2016-03-24 20:34:36 +00:00
}
})
}
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Convert Error into meta data.
const exceptionToMeta = function (sender, contextId, error) {
2016-01-12 02:40:23 +00:00
return {
type: 'exception',
value: errorUtils.serialize(error)
2016-03-24 20:34:36 +00:00
}
}
2016-01-12 02:40:23 +00:00
const throwRPCError = function (message) {
const error = new Error(message)
error.code = 'EBADRPC'
2016-11-17 18:22:29 +00:00
error.errno = -72
throw error
}
const removeRemoteListenersAndLogWarning = (sender, meta, callIntoRenderer) => {
let message = `Attempting to call a function in a renderer window that has been closed or released.` +
2017-01-06 22:14:52 +00:00
`\nFunction provided here: ${meta.location}`
if (sender instanceof EventEmitter) {
const remoteEvents = sender.eventNames().filter((eventName) => {
return sender.listeners(eventName).includes(callIntoRenderer)
2017-01-13 20:28:11 +00:00
})
if (remoteEvents.length > 0) {
message += `\nRemote event names: ${remoteEvents.join(', ')}`
remoteEvents.forEach((eventName) => {
sender.removeListener(eventName, callIntoRenderer)
})
}
}
console.warn(message)
}
2016-01-14 18:35:29 +00:00
// Convert array of meta data from renderer into array of real values.
const unwrapArgs = function (sender, contextId, args) {
const metaToValue = function (meta) {
2016-01-12 02:40:23 +00:00
switch (meta.type) {
case 'value':
2016-03-24 20:34:36 +00:00
return meta.value
2016-01-12 02:40:23 +00:00
case 'remote-object':
2016-03-24 20:34:36 +00:00
return objectsRegistry.get(meta.id)
2016-01-12 02:40:23 +00:00
case 'array':
return unwrapArgs(sender, contextId, meta.value)
2016-01-12 02:40:23 +00:00
case 'buffer':
return bufferUtils.metaToBuffer(meta.value)
2016-01-12 02:40:23 +00:00
case 'date':
2016-03-24 20:34:36 +00:00
return new Date(meta.value)
2016-01-12 02:40:23 +00:00
case 'promise':
return Promise.resolve({
then: metaToValue(meta.then)
2016-03-24 20:34:36 +00:00
})
2016-03-25 19:28:43 +00:00
case 'object': {
const ret = {}
2016-03-24 20:34:36 +00:00
Object.defineProperty(ret.constructor, 'name', { value: meta.name })
2018-09-13 16:10:51 +00:00
for (const { name, value } of meta.members) {
ret[name] = metaToValue(value)
2016-03-24 20:34:36 +00:00
}
return ret
2016-03-25 19:28:43 +00:00
}
2016-01-12 02:40:23 +00:00
case 'function-with-return-value':
const returnValue = metaToValue(meta.value)
2016-03-24 20:34:36 +00:00
return function () {
return returnValue
}
2016-03-25 19:28:43 +00:00
case 'function': {
// Merge contextId and meta.id, since meta.id can be the same in
// different webContents.
const objectId = [contextId, meta.id]
2016-01-14 18:35:29 +00:00
// Cache the callbacks in renderer.
if (rendererFunctions.has(objectId)) {
return rendererFunctions.get(objectId)
2016-01-12 02:40:23 +00:00
}
const processId = sender.getProcessId()
const callIntoRenderer = function (...args) {
if (!sender.isDestroyed() && processId === sender.getProcessId()) {
sender.send('ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args))
2016-03-24 20:34:36 +00:00
} else {
removeRemoteListenersAndLogWarning(this, meta, callIntoRenderer)
2016-03-24 20:34:36 +00:00
}
}
Object.defineProperty(callIntoRenderer, 'length', { value: meta.length })
v8Util.setRemoteCallbackFreer(callIntoRenderer, contextId, meta.id, sender)
rendererFunctions.set(objectId, callIntoRenderer)
2016-03-24 20:34:36 +00:00
return callIntoRenderer
2016-03-25 19:28:43 +00:00
}
2016-01-12 02:40:23 +00:00
default:
2016-03-24 20:34:36 +00:00
throw new TypeError(`Unknown type: ${meta.type}`)
2016-01-12 02:40:23 +00:00
}
2016-03-24 20:34:36 +00:00
}
return args.map(metaToValue)
}
2016-01-12 02:40:23 +00:00
2016-01-14 18:44:21 +00:00
// Call a function and send reply asynchronously if it's a an asynchronous
// style function and the caller didn't pass a callback.
const callFunction = function (event, contextId, func, caller, args) {
const funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous')
const funcPassedCallback = typeof args[args.length - 1] === 'function'
2016-01-12 02:40:23 +00:00
try {
if (funcMarkedAsync && !funcPassedCallback) {
2016-03-24 20:34:36 +00:00
args.push(function (ret) {
event.returnValue = valueToMeta(event.sender, contextId, ret, true)
2016-03-24 20:34:36 +00:00
})
func.apply(caller, args)
2016-01-12 02:40:23 +00:00
} else {
const ret = func.apply(caller, args)
return valueToMeta(event.sender, contextId, ret, true)
2016-01-12 02:40:23 +00:00
}
2016-01-19 22:49:40 +00:00
} catch (error) {
2016-01-14 18:44:21 +00:00
// Catch functions thrown further down in function invocation and wrap
// them with the function name so it's easier to trace things like
// `Error processing argument -1.`
const funcName = func.name || 'anonymous'
const err = new Error(`Could not call remote function '${funcName}'. Check that the function signature is correct. Underlying error: ${error.message}`)
err.cause = error
throw err
2016-01-12 02:40:23 +00:00
}
2016-03-24 20:34:36 +00:00
}
2016-01-12 02:40:23 +00:00
const handleRemoteCommand = function (channel, handler) {
ipcMain.on(channel, (event, contextId, ...args) => {
let returnValue
try {
returnValue = handler(event, contextId, ...args)
} catch (error) {
returnValue = exceptionToMeta(event.sender, contextId, error)
}
if (returnValue !== undefined) {
event.returnValue = returnValue
}
})
}
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_REQUIRE', function (event, contextId, module) {
return valueToMeta(event.sender, contextId, process.mainModule.require(module))
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_GET_BUILTIN', function (event, contextId, module) {
return valueToMeta(event.sender, contextId, electron[module])
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_GLOBAL', function (event, contextId, name) {
return valueToMeta(event.sender, contextId, global[name])
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_CURRENT_WINDOW', function (event, contextId) {
return valueToMeta(event.sender, contextId, event.sender.getOwnerBrowserWindow())
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_CURRENT_WEB_CONTENTS', function (event, contextId) {
return valueToMeta(event.sender, contextId, event.sender)
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_CONSTRUCTOR', function (event, contextId, id, args) {
args = unwrapArgs(event.sender, contextId, args)
const constructor = objectsRegistry.get(id)
if (constructor == null) {
throwRPCError(`Cannot call constructor on missing remote object ${id}`)
2016-01-12 02:40:23 +00:00
}
return valueToMeta(event.sender, contextId, new constructor(...args))
})
handleRemoteCommand('ELECTRON_BROWSER_FUNCTION_CALL', function (event, contextId, id, args) {
args = unwrapArgs(event.sender, contextId, args)
const func = objectsRegistry.get(id)
if (func == null) {
throwRPCError(`Cannot call function on missing remote object ${id}`)
2016-01-12 02:40:23 +00:00
}
return callFunction(event, contextId, func, global, args)
})
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CONSTRUCTOR', function (event, contextId, id, method, args) {
args = unwrapArgs(event.sender, contextId, args)
const object = objectsRegistry.get(id)
2016-01-12 02:40:23 +00:00
if (object == null) {
throwRPCError(`Cannot call constructor '${method}' on missing remote object ${id}`)
2016-01-12 02:40:23 +00:00
}
return valueToMeta(event.sender, contextId, new object[method](...args))
})
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_CALL', function (event, contextId, id, method, args) {
args = unwrapArgs(event.sender, contextId, args)
const obj = objectsRegistry.get(id)
if (obj == null) {
throwRPCError(`Cannot call function '${method}' on missing remote object ${id}`)
2016-01-12 02:40:23 +00:00
}
return callFunction(event, contextId, obj[method], obj, args)
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_SET', function (event, contextId, id, name, args) {
args = unwrapArgs(event.sender, contextId, args)
const obj = objectsRegistry.get(id)
if (obj == null) {
throwRPCError(`Cannot set property '${name}' on missing remote object ${id}`)
2016-01-12 02:40:23 +00:00
}
obj[name] = args[0]
return null
})
handleRemoteCommand('ELECTRON_BROWSER_MEMBER_GET', function (event, contextId, id, name) {
const obj = objectsRegistry.get(id)
if (obj == null) {
throwRPCError(`Cannot get property '${name}' on missing remote object ${id}`)
2016-01-12 02:40:23 +00:00
}
return valueToMeta(event.sender, contextId, obj[name])
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_DEREFERENCE', function (event, contextId, id) {
objectsRegistry.remove(event.sender, contextId, id)
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
handleRemoteCommand('ELECTRON_BROWSER_CONTEXT_RELEASE', (event, contextId) => {
objectsRegistry.clear(event.sender, contextId)
return null
})
handleRemoteCommand('ELECTRON_BROWSER_GUEST_WEB_CONTENTS', function (event, contextId, guestInstanceId) {
const guestViewManager = require('@electron/internal/browser/guest-view-manager')
return valueToMeta(event.sender, contextId, guestViewManager.getGuest(guestInstanceId))
2016-03-24 20:34:36 +00:00
})
2016-01-12 02:40:23 +00:00
ipcMain.on('ELECTRON_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function (event, requestId, guestInstanceId, method, args, hasCallback) {
new Promise(resolve => {
const guestViewManager = require('./guest-view-manager')
const guest = guestViewManager.getGuest(guestInstanceId)
if (guest.hostWebContents !== event.sender) {
throw new Error('Access denied')
}
if (hasCallback) {
guest[method](...args, resolve)
} else {
resolve(guest[method](...args))
}
}).then(result => {
return [null, result]
}, error => {
return [errorUtils.serialize(error)]
}).then(responseArgs => {
event.sender.send(`ELECTRON_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, ...responseArgs)
})
})
ipcMain.on('ELECTRON_BROWSER_SYNC_CALL_TO_GUEST_VIEW', function (event, guestInstanceId, method, args) {
2016-01-12 02:40:23 +00:00
try {
const guestViewManager = require('@electron/internal/browser/guest-view-manager')
const guest = guestViewManager.getGuest(guestInstanceId)
if (guest.hostWebContents !== event.sender) {
throw new Error('Access denied')
}
event.returnValue = [null, guest[method].apply(guest, args)]
2016-01-19 22:49:40 +00:00
} catch (error) {
event.returnValue = [errorUtils.serialize(error)]
2016-01-12 02:40:23 +00:00
}
2016-03-24 20:34:36 +00:00
})
2016-05-18 12:19:50 +00:00
// Implements window.close()
ipcMain.on('ELECTRON_BROWSER_WINDOW_CLOSE', function (event) {
2017-08-17 17:56:37 +00:00
const window = event.sender.getOwnerBrowserWindow()
if (window) {
window.close()
}
2017-08-17 17:56:37 +00:00
event.returnValue = null
})
const getTempDirectory = function () {
try {
return electron.app.getPath('temp')
} catch (error) {
return os.tmpdir()
}
}
ipcMain.on('ELECTRON_CRASH_REPORTER_INIT', function (event, options) {
const productName = options.productName || electron.app.getName()
const crashesDirectory = path.join(getTempDirectory(), `${productName} Crashes`)
if (process.platform === 'win32') {
const env = {
ELECTRON_INTERNAL_CRASH_SERVICE: 1
}
const args = [
'--reporter-url=' + options.submitURL,
'--application-name=' + productName,
'--crashes-directory=' + crashesDirectory,
'--v=1'
]
spawn(process.helperExecPath, args, {
env,
detached: true
})
}
event.returnValue = {
productName,
crashesDirectory,
appVersion: electron.app.getVersion()
}
})
ipcMain.on('ELECTRON_BROWSER_SANDBOX_LOAD', function (event) {
const preloadPath = event.sender._getPreloadPath()
let preloadSrc = null
let preloadError = null
if (preloadPath) {
try {
preloadSrc = fs.readFileSync(preloadPath).toString()
} catch (err) {
2018-09-13 16:10:51 +00:00
preloadError = { stack: err ? err.stack : (new Error(`Failed to load "${preloadPath}"`)).stack }
}
}
event.returnValue = {
preloadSrc,
preloadError,
process: {
arch: process.arch,
platform: process.platform,
env: process.env,
version: process.version,
versions: process.versions
}
}
})