alljoyn-15.09a+dfsg.1/0000755000175000017500000000000012620747066013657 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/0000755000175000017500000000000012620747066016023 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/js/0000755000175000017500000000000012620747066016437 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/js/npapi/0000755000175000017500000000000012620747066017546 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/js/npapi/alljoyn_init.js0000644000175000017500000000735212620747066022606 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ (function() { var bus = null, permissionLevel, requestPermission, found, i; /* * Check if AllJoyn is already initialized. */ if (window.org && window.org.alljoyn) { return; } if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes['application/x-alljoyn']) { /* * Create an object element that will load the AllJoyn plugin. */ bus = document.createElement('object'); bus.type = 'application/x-alljoyn'; /* * Hide the element. It's necessary to use the method below instead of changing the * visibility to ensure that the plugin has a top-level window for the permission request * dialog. */ bus.style.position = 'absolute'; bus.style.left = 0; bus.style.top = -500; bus.style.width = 1; bus.style.height = 1; bus.style.overflow = 'hidden'; document.documentElement.appendChild(bus); /* * Check that everything was loaded correctly. */ if (bus && (typeof bus.BusAttachment === 'undefined')) { bus = null; } } if (!bus) { return; } /* * Put the AllJoyn namespace object in the right place. */ if (!window.org) { org = {}; } if (!window.org.alljoyn) { window.org.alljoyn = {bus: bus}; } /* * Until the feature permissions API is supported and available to the plugin, use the fallback * implementation in the plugin. */ if (!window.navigator.USER_ALLOWED) { window.navigator.USER_ALLOWED = bus.USER_ALLOWED; window.navigator.DEFAULT_ALLOWED = bus.DEFAULT_ALLOWED; window.navigator.DEFAULT_DENIED = bus.DEFAULT_DENIED; window.navigator.USER_DENIED = bus.USER_DENIED; } permissionLevel = window.navigator.permissionLevel; window.navigator.permissionLevel = function(feature) { if (feature === 'org.alljoyn.bus') { return bus.permissionLevel(feature); } else { return permissionLevel(feature); } } requestPermission = window.navigator.requestPermission; window.navigator.requestPermission = function(feature, callback) { if (feature === 'org.alljoyn.bus') { return bus.requestPermission(feature, callback); } else { return requestPermission(feature, callback); } } found = false; for (i = 0; window.navigator.privilegedFeatures && (i < window.navigator.privilegedFeatures.length); ++i) { if (window.navigator.privilegedFeatures[i] === 'org.alljoyn.bus') { found = true; } } if (!found) { if (window.navigator.privilegedFeatures) { window.navigator.privilegedFeatures.push('org.alljoyn.bus'); } else { window.navigator.privilegedFeatures = bus.privilegedFeatures; } } })(); alljoyn-15.09a+dfsg.1/alljoyn_js/jni/0000755000175000017500000000000012620747066016603 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/jni/CredentialsInterface.cc0000644000175000017500000000327612620747066023200 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "CredentialsInterface.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _CredentialsInterface::constants; std::map& _CredentialsInterface::Constants() { if (constants.empty()) { CONSTANT("PASSWORD", 0x0001); CONSTANT("USER_NAME", 0x0002); CONSTANT("CERT_CHAIN", 0x0004); CONSTANT("PRIVATE_KEY", 0x0008); CONSTANT("LOGON_ENTRY", 0x0010); CONSTANT("EXPIRATION", 0x0020); CONSTANT("NEW_PASSWORD", 0x1001); CONSTANT("ONE_TIME_PWD", 0x2001); } return constants; } _CredentialsInterface::_CredentialsInterface(Plugin& plugin) : ScriptableObject(plugin, Constants()) { QCC_DbgTrace(("%s", __FUNCTION__)); } _CredentialsInterface::~_CredentialsInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/CallbackNative.cc0000644000175000017500000005363112620747066021765 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "CallbackNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" CallbackNative::CallbackNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } CallbackNative::~CallbackNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void CallbackNative::onCallback(BusErrorHost& busError) { QCC_DbgTrace(("%s", __FUNCTION__)); NPVariant nparg; ToHostObject(plugin, busError, nparg); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, &nparg, 1, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&nparg); } void CallbackNative::onCallback(QStatus status) { QCC_DbgTrace(("%s(status=%s)", __FUNCTION__, QCC_StatusText(status))); NPVariant nparg; if (ER_OK == status) { VOID_TO_NPVARIANT(nparg); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, nparg); } NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, &nparg, 1, &result); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, qcc::String& s) { QCC_DbgTrace(("%s(status=%s,s=%s)", __FUNCTION__, QCC_StatusText(status), s.c_str())); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToDOMString(plugin, s, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[1]); } void CallbackNative::onCallback(QStatus status, uint32_t u) { QCC_DbgTrace(("%s(status=%s,u=%d)", __FUNCTION__, QCC_StatusText(status), u)); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToUnsignedLong(plugin, u, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, bool b) { QCC_DbgTrace(("%s(status=%s,b=%d)", __FUNCTION__, QCC_StatusText(status), b)); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToBoolean(plugin, b, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, ajn::SessionId id, SessionOptsHost& opts) { QCC_DbgTrace(("%s(status=%s,id=%d)", __FUNCTION__, QCC_StatusText(status), id)); NPVariant npargs[3]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToUnsignedLong(plugin, id, npargs[1]); ToHostObject(plugin, opts, npargs[2]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 3, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); } void CallbackNative::onCallback(QStatus status, ajn::SessionPort port) { QCC_DbgTrace(("%s(status=%s,port=%d)", __FUNCTION__, QCC_StatusText(status), port)); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToUnsignedShort(plugin, port, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, MessageHost& message, const ajn::MsgArg* args, size_t numArgs) { QCC_DbgTrace(("%s(status=%s,args=%p,numArgs=%d)", __FUNCTION__, QCC_StatusText(status), args, numArgs)); #if !defined(NDEBUG) qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); #endif QStatus sts = ER_OK; uint32_t npargCount = 2 + numArgs; NPVariant* npargs = new NPVariant[npargCount]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToHostObject(plugin, message, npargs[1]); size_t i; for (i = 0; (ER_OK == sts) && (i < numArgs); ++i) { ToAny(plugin, args[i], npargs[2 + i], sts); } NPVariant result = NPVARIANT_VOID; if (ER_OK == sts) { if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, npargCount, &result)) { sts = ER_FAIL; QCC_LogError(sts, ("NPN_InvokeDefault failed")); } } else { npargCount = 2 + i; } for (uint32_t j = 0; j < npargCount; ++j) { NPN_ReleaseVariantValue(&npargs[j]); } delete[] npargs; NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, AboutObjHost& aboutObj) { QCC_DbgTrace(("%s(status=%s)", __FUNCTION__, QCC_StatusText(status))); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToHostObject(plugin, aboutObj, npargs[1]); NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, ProxyBusObjectHost& proxyBusObject) { QCC_DbgTrace(("%s(status=%s)", __FUNCTION__, QCC_StatusText(status))); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToHostObject(plugin, proxyBusObject, npargs[1]); NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, SocketFdHost& socketFd) { QCC_DbgTrace(("%s(status=%s)", __FUNCTION__, QCC_StatusText(status))); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToHostObject(plugin, socketFd, npargs[1]); NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, InterfaceDescriptionNative* interfaceDescription) { QCC_DbgTrace(("%s(status=%s)", __FUNCTION__, QCC_StatusText(status))); NPVariant npargs[2]; if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } ToNativeObject(plugin, interfaceDescription, npargs[1]); NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, InterfaceDescriptionNative** interfaceDescriptions, size_t numInterfaces) { QCC_DbgTrace(("%s(status=%s,numInterfaces=%d)", __FUNCTION__, QCC_StatusText(status), numInterfaces)); NPVariant element = NPVARIANT_VOID; NPVariant npargs[2]; if (!NewArray(plugin, npargs[1])) { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); } for (size_t i = 0; (ER_OK == status) && (i < numInterfaces); ++i) { ToNativeObject(plugin, interfaceDescriptions[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(npargs[1]), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); VOID_TO_NPVARIANT(element); } if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&element); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&result); } void CallbackNative::onCallback(QStatus status, std::vector& children) { QCC_DbgTrace(("%s(status=%s,children.size()=%d)", __FUNCTION__, QCC_StatusText(status), children.size())); NPVariant element = NPVARIANT_VOID; NPVariant npargs[2]; if (!NewArray(plugin, npargs[1])) { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); } for (size_t i = 0; (ER_OK == status) && (i < children.size()); ++i) { ToHostObject(plugin, children[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(npargs[1]), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); VOID_TO_NPVARIANT(element); } if (ER_OK == status) { VOID_TO_NPVARIANT(npargs[0]); } else { BusErrorHost busError(plugin, status); ToHostObject(plugin, busError, npargs[0]); } NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&element); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&result); } class CallbackContext : public PluginData::CallbackContext { public: CallbackNative* callbackNative; QStatus status; CallbackContext(CallbackNative* callbackNative, QStatus status) : callbackNative(callbackNative), status(status) { } virtual ~CallbackContext() { delete callbackNative; } }; class StatusCallbackContext : public CallbackContext { public: StatusCallbackContext(CallbackNative* callbackNative, QStatus status) : CallbackContext(callbackNative, status) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status) { PluginData::Callback callback(plugin, _StatusCallbackCB); callback->context = new StatusCallbackContext(callbackNative, status); PluginData::DispatchCallback(callback); } void CallbackNative::_StatusCallbackCB(PluginData::CallbackContext* ctx) { StatusCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status); } class StringCallbackContext : public CallbackContext { public: qcc::String s; StringCallbackContext(CallbackNative* callbackNative, QStatus status, qcc::String& s) : CallbackContext(callbackNative, status), s(s) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, qcc::String& s) { PluginData::Callback callback(plugin, _StringCallbackCB); callback->context = new StringCallbackContext(callbackNative, status, s); PluginData::DispatchCallback(callback); } void CallbackNative::_StringCallbackCB(PluginData::CallbackContext* ctx) { StringCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->s); } class UnsignedLongCallbackContext : public CallbackContext { public: uint32_t u; UnsignedLongCallbackContext(CallbackNative* callbackNative, QStatus status, uint32_t u) : CallbackContext(callbackNative, status), u(u) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, uint32_t u) { PluginData::Callback callback(plugin, _UnsignedLongCallbackCB); callback->context = new UnsignedLongCallbackContext(callbackNative, status, u); PluginData::DispatchCallback(callback); } void CallbackNative::_UnsignedLongCallbackCB(PluginData::CallbackContext* ctx) { UnsignedLongCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->u); } class BoolCallbackContext : public CallbackContext { public: bool b; BoolCallbackContext(CallbackNative* callbackNative, QStatus status, bool b) : CallbackContext(callbackNative, status), b(b) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, bool b) { PluginData::Callback callback(plugin, _BoolCallbackCB); callback->context = new BoolCallbackContext(callbackNative, status, b); PluginData::DispatchCallback(callback); } void CallbackNative::_BoolCallbackCB(PluginData::CallbackContext* ctx) { BoolCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->b); } class BindSessionPortCallbackContext : public CallbackContext { public: ajn::SessionPort port; BindSessionPortCallbackContext(CallbackNative* callbackNative, QStatus status, ajn::SessionPort port) : CallbackContext(callbackNative, status), port(port) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, ajn::SessionPort port) { PluginData::Callback callback(plugin, _BindSessionPortCallbackCB); callback->context = new BindSessionPortCallbackContext(callbackNative, status, port); PluginData::DispatchCallback(callback); } void CallbackNative::_BindSessionPortCallbackCB(PluginData::CallbackContext* ctx) { BindSessionPortCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->port); } class GetAboutObjectCallbackContext : public CallbackContext { public: AboutObjHost aboutObj; GetAboutObjectCallbackContext(CallbackNative* callbackNative, QStatus status, AboutObjHost& aboutObj) : CallbackContext(callbackNative, status), aboutObj(aboutObj) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, AboutObjHost& aboutObj) { PluginData::Callback callback(plugin, _GetAboutObjectCallbackCB); callback->context = new GetAboutObjectCallbackContext(callbackNative, status, aboutObj); PluginData::DispatchCallback(callback); } void CallbackNative::_GetAboutObjectCallbackCB(PluginData::CallbackContext* ctx) { GetAboutObjectCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->aboutObj); } class GetProxyBusObjectCallbackContext : public CallbackContext { public: ProxyBusObjectHost proxyBusObject; GetProxyBusObjectCallbackContext(CallbackNative* callbackNative, QStatus status, ProxyBusObjectHost& proxyBusObject) : CallbackContext(callbackNative, status), proxyBusObject(proxyBusObject) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, ProxyBusObjectHost& proxyBusObject) { PluginData::Callback callback(plugin, _GetProxyBusObjectCallbackCB); callback->context = new GetProxyBusObjectCallbackContext(callbackNative, status, proxyBusObject); PluginData::DispatchCallback(callback); } void CallbackNative::_GetProxyBusObjectCallbackCB(PluginData::CallbackContext* ctx) { GetProxyBusObjectCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->proxyBusObject); } class GetSessionFdCallbackContext : public CallbackContext { public: SocketFdHost socketFd; GetSessionFdCallbackContext(CallbackNative* callbackNative, QStatus status, SocketFdHost& socketFd) : CallbackContext(callbackNative, status), socketFd(socketFd) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, SocketFdHost& socketFd) { PluginData::Callback callback(plugin, _GetSessionFdCallbackCB); callback->context = new GetSessionFdCallbackContext(callbackNative, status, socketFd); PluginData::DispatchCallback(callback); } void CallbackNative::_GetSessionFdCallbackCB(PluginData::CallbackContext* ctx) { GetSessionFdCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->socketFd); } class GetInterfaceCallbackContext : public CallbackContext { public: InterfaceDescriptionNative* interfaceDescription; GetInterfaceCallbackContext(CallbackNative* callbackNative, QStatus status, InterfaceDescriptionNative* interfaceDescription) : CallbackContext(callbackNative, status), interfaceDescription(interfaceDescription) { } ~GetInterfaceCallbackContext() { delete interfaceDescription; } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, InterfaceDescriptionNative* interfaceDescription) { PluginData::Callback callback(plugin, _GetInterfaceCallbackCB); callback->context = new GetInterfaceCallbackContext(callbackNative, status, interfaceDescription); PluginData::DispatchCallback(callback); } void CallbackNative::_GetInterfaceCallbackCB(PluginData::CallbackContext* ctx) { GetInterfaceCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->interfaceDescription); } class GetInterfacesCallbackContext : public CallbackContext { public: InterfaceDescriptionNative** interfaceDescriptions; size_t numInterfaces; GetInterfacesCallbackContext(CallbackNative* callbackNative, QStatus status, InterfaceDescriptionNative** interfaceDescriptions, size_t numInterfaces) : CallbackContext(callbackNative, status), numInterfaces(numInterfaces) { this->interfaceDescriptions = new InterfaceDescriptionNative*[numInterfaces]; for (size_t i = 0; i < numInterfaces; ++i) { this->interfaceDescriptions[i] = interfaceDescriptions[i]; } } ~GetInterfacesCallbackContext() { for (size_t i = 0; i < numInterfaces; ++i) { delete interfaceDescriptions[i]; } delete[] interfaceDescriptions; } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, InterfaceDescriptionNative** interfaceDescriptions, size_t numInterfaces) { PluginData::Callback callback(plugin, _GetInterfacesCallbackCB); callback->context = new GetInterfacesCallbackContext(callbackNative, status, interfaceDescriptions, numInterfaces); PluginData::DispatchCallback(callback); } void CallbackNative::_GetInterfacesCallbackCB(PluginData::CallbackContext* ctx) { GetInterfacesCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->interfaceDescriptions, context->numInterfaces); } class GetChildrenCallbackContext : public CallbackContext { public: std::vector children; GetChildrenCallbackContext(CallbackNative* callbackNative, QStatus status, std::vector& children) : CallbackContext(callbackNative, status), children(children) { } }; void CallbackNative::DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, std::vector& children) { PluginData::Callback callback(plugin, _GetChildrenCallbackCB); callback->context = new GetChildrenCallbackContext(callbackNative, status, children); PluginData::DispatchCallback(callback); } void CallbackNative::_GetChildrenCallbackCB(PluginData::CallbackContext* ctx) { GetChildrenCallbackContext* context = static_cast(ctx); context->callbackNative->onCallback(context->status, context->children); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageReplyHost.h0000644000175000017500000000314412620747066022214 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _MESSAGEREPLYHOST_H #define _MESSAGEREPLYHOST_H #include "BusAttachment.h" #include "BusObject.h" #include "MessageHost.h" #include "ScriptableObject.h" #include #include #include class _MessageReplyHost : public _MessageHost { public: _MessageReplyHost(Plugin& plugin, BusAttachment& busAttachment, BusObject& busObject, ajn::Message& message, qcc::String replySignature); virtual ~_MessageReplyHost(); private: BusObject busObject; qcc::String replySignature; bool reply(const NPVariant* npargs, uint32_t npargCount, NPVariant* npresult); bool replyError(const NPVariant* npargs, uint32_t npargCount, NPVariant* npresult); }; typedef qcc::ManagedObj<_MessageReplyHost> MessageReplyHost; #endif // _MESSAGEREPLYHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HttpServer.cc0000644000175000017500000004163612620747066021232 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "HttpServer.h" #include "HttpListenerNative.h" #include "PluginData.h" #include #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" static const uint8_t hex[] = "0123456789ABCDEF"; static const size_t maxData = 8192; static const size_t maxHdr = 8; static void ParseRequest(const qcc::String& line, qcc::String& method, qcc::String& requestUri, qcc::String& httpVersion) { size_t pos = 0; size_t begin = 0; do { size_t sp = line.find_first_of(' ', begin); if (qcc::String::npos == sp) { sp = line.size(); } qcc::String token = line.substr(begin, sp - begin); switch (pos++) { case 0: method = token; break; case 1: requestUri = token; break; case 2: httpVersion = token; break; default: break; } begin = sp + 1; } while (begin < line.size()); } static QStatus PushBytes(qcc::SocketStream& stream, const char* buf, size_t numBytes) { /* * TODO It looks like PushBytes on SocketStream is not guaranteed to send all the bytes, * but it also looks like our existing code relies on that. What am I missing? */ QStatus status = ER_OK; size_t numSent = 0; for (size_t pos = 0; pos < numBytes; pos += numSent) { status = stream.PushBytes(&buf[pos], numBytes - pos, numSent); if (ER_OK != status) { QCC_LogError(status, ("PushBytes failed")); break; } } return status; } static QStatus SendBadRequestResponse(qcc::SocketStream& stream) { qcc::String response = "HTTP/1.1 400 Bad Request\r\n"; QStatus status = PushBytes(stream, response.data(), response.size()); if (ER_OK == status) { QCC_DbgTrace(("[%d] %s", stream.GetSocketFd(), response.c_str())); } return status; } static QStatus SendNotFoundResponse(qcc::SocketStream& stream) { qcc::String response = "HTTP/1.1 404 Not Found\r\n"; QStatus status = PushBytes(stream, response.data(), response.size()); if (ER_OK == status) { QCC_DbgTrace(("[%d] %s", stream.GetSocketFd(), response.c_str())); } return status; } _HttpServer::RequestThread::RequestThread(_HttpServer* httpServer, qcc::SocketFd requestFd) : httpServer(httpServer), stream(requestFd) { QCC_DbgTrace(("%s", __FUNCTION__)); stream.SetSendTimeout(qcc::Event::WAIT_FOREVER); } class OnRequestContext : public PluginData::CallbackContext { public: Plugin plugin; HttpServer httpServer; qcc::String requestUri; Http::Headers requestHeaders; qcc::SocketStream stream; qcc::SocketFd sessionFd; OnRequestContext(Plugin& plugin, _HttpServer* httpServer, qcc::String& requestUri, Http::Headers& requestHeaders, qcc::SocketStream& stream, qcc::SocketFd sessionFd) : plugin(plugin), httpServer(HttpServer::wrap(httpServer)), requestUri(requestUri), requestHeaders(requestHeaders), stream(stream), sessionFd(sessionFd) { } }; static void _OnRequest(PluginData::CallbackContext* ctx) { OnRequestContext* context = static_cast(ctx); HttpListenerNative* httpListener = context->httpServer->GetObjectUrl(context->requestUri).httpListener; if (httpListener) { HttpRequestHost httpRequest(context->plugin, context->httpServer, context->requestHeaders, context->stream, context->sessionFd); httpListener->onRequest(httpRequest); } else { /* Send the default response */ uint16_t status = 200; qcc::String statusText = "OK"; Http::Headers responseHeaders; responseHeaders["Date"] = qcc::UTCTime(); responseHeaders["Content-Type"] = "application/octet-stream"; context->httpServer->SendResponse(context->stream, status, statusText, responseHeaders, context->sessionFd); } } qcc::ThreadReturn STDCALL _HttpServer::RequestThread::Run(void* arg) { QCC_UNUSED(arg); QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String line; QStatus status; qcc::String method, requestUri, httpVersion; qcc::SocketFd sessionFd = qcc::INVALID_SOCKET_FD; Http::Headers requestHeaders; PluginData::Callback callback(httpServer->plugin, _OnRequest); status = stream.GetLine(line); if (ER_OK != status) { SendBadRequestResponse(stream); goto exit; } QCC_DbgTrace(("[%d] %s", stream.GetSocketFd(), line.c_str())); ParseRequest(line, method, requestUri, httpVersion); if (method != "GET") { SendBadRequestResponse(stream); goto exit; } sessionFd = httpServer->GetObjectUrl(requestUri).fd; if (qcc::INVALID_SOCKET_FD == sessionFd) { SendNotFoundResponse(stream); goto exit; } /* * Read (and discard) the rest of the request headers. */ while ((ER_OK == status) && !line.empty()) { line.clear(); status = stream.GetLine(line); if (ER_OK == status) { size_t begin; size_t pos = 0; while ((pos < line.size()) && isspace(line[pos])) ++pos; begin = pos; while ((pos < line.size()) && !isspace(line[pos]) && (':' != line[pos])) ++pos; qcc::String header = line.substr(begin, pos - begin); while ((pos < line.size()) && (isspace(line[pos]) || (':' == line[pos]))) ++pos; begin = pos; qcc::String value = line.substr(begin); QCC_DbgTrace(("[%d] %s", stream.GetSocketFd(), line.c_str())); if (!header.empty() || !value.empty()) { requestHeaders[header] = value; } } } if (ER_OK != status) { SendBadRequestResponse(stream); goto exit; } callback->context = new OnRequestContext(httpServer->plugin, httpServer, requestUri, requestHeaders, stream, sessionFd); PluginData::DispatchCallback(callback); exit: if (ER_OK != status) { QCC_LogError(status, ("Request thread exiting")); } return 0; } _HttpServer::ResponseThread::ResponseThread(_HttpServer* httpServer, qcc::SocketStream& stream, uint16_t status, qcc::String& statusText, Http::Headers& responseHeaders, qcc::SocketFd sessionFd) : httpServer(httpServer), stream(stream), status(status), statusText(statusText), responseHeaders(responseHeaders), sessionFd(sessionFd) { QCC_DbgTrace(("%s", __FUNCTION__)); } qcc::ThreadReturn STDCALL _HttpServer::ResponseThread::Run(void* arg) { QCC_UNUSED(arg); QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String response; QStatus sts; char* buffer = new char[maxHdr + maxData + 2]; response = "HTTP/1.1 " + qcc::U32ToString(status) + " " + statusText + "\r\n"; for (Http::Headers::iterator it = responseHeaders.begin(); it != responseHeaders.end(); ++it) { response += it->first + ": " + it->second + "\r\n"; } response += "\r\n"; sts = PushBytes(stream, response.data(), response.size()); if (ER_OK != sts) { goto exit; } QCC_DbgTrace(("[%d] %s", stream.GetSocketFd(), response.c_str())); /* * Now pump out data. */ while (ER_OK == sts) { size_t received = 0; char* ptr = &buffer[maxHdr]; sts = qcc::Recv(sessionFd, ptr, maxData, received); if (ER_OK == sts) { if (0 == received) { if (responseHeaders["Transfer-Encoding"] == "chunked") { sts = PushBytes(stream, "0\r\n", 3); if (ER_OK != sts) { QCC_LogError(sts, ("PushBytes failed")); } } sts = ER_SOCK_OTHER_END_CLOSED; QCC_LogError(sts, ("Recv failed")); } else { size_t len; if (responseHeaders["Transfer-Encoding"] == "chunked") { /* Chunk length header is ascii hex followed by cr-lf */ *(--ptr) = '\n'; *(--ptr) = '\r'; len = 2; size_t n = received; do { *(--ptr) = hex[n & 0xF]; n >>= 4; ++len; } while (n); /* Chunk is terminated with cr-lf */ len += received; ptr[len++] = '\r'; ptr[len++] = '\n'; } else { len = received; } sts = PushBytes(stream, ptr, len); if (ER_OK != sts) { QCC_LogError(sts, ("PushBytes failed")); } } } else if (ER_WOULDBLOCK == sts) { qcc::Event recvEvent(sessionFd, qcc::Event::IO_READ); sts = qcc::Event::Wait(recvEvent); if (ER_OK != sts) { QCC_LogError(sts, ("Wait failed")); } } else { QCC_LogError(sts, ("Recv failed")); } } exit: delete[] buffer; if (ER_OK != sts) { QCC_LogError(sts, ("Response thread exiting")); } return 0; } _HttpServer::_HttpServer(Plugin& plugin) : plugin(plugin) { QCC_DbgTrace(("%s", __FUNCTION__)); } _HttpServer::~_HttpServer() { QCC_DbgTrace(("%s", __FUNCTION__)); lock.Lock(); std::vector::iterator tit; for (tit = threads.begin(); tit != threads.end(); ++tit) { (*tit)->Stop(); } lock.Unlock(); Stop(); lock.Lock(); while (threads.size() > 0) { lock.Unlock(); qcc::Sleep(50); lock.Lock(); } lock.Unlock(); Join(); std::map::iterator oit; for (oit = objectUrls.begin(); oit != objectUrls.end(); ++oit) { QCC_DbgTrace(("Removed %s -> %d", oit->first.c_str(), oit->second.fd)); qcc::Close(oit->second.fd); delete oit->second.httpListener; } QCC_DbgTrace(("-%s", __FUNCTION__)); } void _HttpServer::ThreadExit(qcc::Thread* thread) { QCC_DbgTrace(("%s", __FUNCTION__)); RequestThread* requestThread = static_cast(thread); lock.Lock(); std::vector::iterator it = std::find(threads.begin(), threads.end(), requestThread); if (it != threads.end()) { threads.erase(it); } lock.Unlock(); delete requestThread; } QStatus _HttpServer::CreateObjectUrl(qcc::SocketFd fd, HttpListenerNative* httpListener, qcc::String& url) { QCC_DbgTrace(("%s(fd=%d)", __FUNCTION__, fd)); QStatus status; qcc::SocketFd sessionFd = qcc::INVALID_SOCKET_FD; qcc::String requestUri; status = Start(); if (ER_OK != status) { goto exit; } status = qcc::SocketDup(fd, sessionFd); if (ER_OK != status) { QCC_LogError(status, ("SocketDup failed")); goto exit; } requestUri = "/" + qcc::RandHexString(256); lock.Lock(); objectUrls[requestUri] = ObjectUrl(sessionFd, httpListener); lock.Unlock(); QCC_DbgTrace(("Added %s -> %d", requestUri.c_str(), sessionFd)); url = origin + requestUri; exit: if (ER_OK != status) { if (qcc::INVALID_SOCKET_FD != sessionFd) { qcc::Close(sessionFd); delete httpListener; } } return status; } void _HttpServer::RevokeObjectUrl(const qcc::String& url) { QCC_DbgTrace(("%s(url=%s)", __FUNCTION__, url.c_str())); qcc::SocketFd sessionFd = qcc::INVALID_SOCKET_FD; HttpListenerNative* httpListener = NULL; qcc::String requestUri = url.substr(url.find_last_of('/')); lock.Lock(); std::map::iterator it = objectUrls.find(requestUri); if (it != objectUrls.end()) { sessionFd = it->second.fd; httpListener = it->second.httpListener; objectUrls.erase(it); } lock.Unlock(); QCC_DbgTrace(("Removed %s -> %d", requestUri.c_str(), sessionFd)); if (qcc::INVALID_SOCKET_FD != sessionFd) { qcc::Close(sessionFd); delete httpListener; } } QStatus _HttpServer::Start() { QCC_DbgTrace(("%s", __FUNCTION__)); if (IsStopping()) { return ER_THREAD_STOPPING; } else if (IsRunning()) { return ER_OK; } QStatus status; qcc::SocketFd listenFd = qcc::INVALID_SOCKET_FD; qcc::IPAddress localhost("127.0.0.1"); uint16_t listenPort = 0; status = qcc::Socket(qcc::QCC_AF_INET, qcc::QCC_SOCK_STREAM, listenFd); if (ER_OK != status) { QCC_LogError(status, ("Socket failed")); goto exit; } status = qcc::Bind(listenFd, localhost, listenPort); if (ER_OK != status) { QCC_LogError(status, ("Find failed")); goto exit; } status = qcc::GetLocalAddress(listenFd, localhost, listenPort); if (ER_OK != status) { QCC_LogError(status, ("GetLocalAddress failed")); goto exit; } status = qcc::Listen(listenFd, SOMAXCONN); if (ER_OK != status) { QCC_LogError(status, ("Listen failed")); goto exit; } status = qcc::SetBlocking(listenFd, false); if (ER_OK != status) { QCC_LogError(status, ("SetBlocking(false) failed")); goto exit; } status = qcc::Thread::Start(reinterpret_cast(listenFd)); if (ER_OK != status) { QCC_LogError(status, ("Start failed")); goto exit; } origin = "http://" + localhost.ToString() + ":" + qcc::U32ToString(listenPort); QCC_DbgTrace(("%s", origin.c_str())); exit: if (ER_OK != status) { if (qcc::INVALID_SOCKET_FD != listenFd) { qcc::Close(listenFd); } } return status; } _HttpServer::ObjectUrl _HttpServer::GetObjectUrl(const qcc::String& requestUri) { QCC_DbgTrace(("%s", __FUNCTION__)); lock.Lock(); ObjectUrl objectUrl; std::map::iterator it = objectUrls.find(requestUri); if (it != objectUrls.end()) { objectUrl = it->second; } lock.Unlock(); return objectUrl; } void _HttpServer::SendResponse(qcc::SocketStream& stream, uint16_t status, qcc::String& statusText, Http::Headers& responseHeaders, qcc::SocketFd fd) { QCC_DbgTrace(("%s", __FUNCTION__)); ResponseThread* responseThread = new ResponseThread(this, stream, status, statusText, responseHeaders, fd); QStatus sts = responseThread->Start(NULL, this); if (ER_OK == sts) { lock.Lock(); threads.push_back(responseThread); lock.Unlock(); } else { QCC_LogError(sts, ("Start response thread failed")); delete responseThread; } } qcc::ThreadReturn STDCALL _HttpServer::Run(void* arg) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::SocketFd listenFd = reinterpret_cast(arg); QStatus status = ER_OK; while (!IsStopping()) { qcc::SocketFd requestFd; do { qcc::IPAddress addr; uint16_t remotePort; status = qcc::Accept(listenFd, addr, remotePort, requestFd); if (ER_OK == status) { break; } else if (ER_WOULDBLOCK == status) { qcc::Event listenEvent(listenFd, qcc::Event::IO_READ); status = qcc::Event::Wait(listenEvent); } else { QCC_LogError(status, ("Accept failed")); status = ER_OK; } } while (ER_OK == status); if (ER_OK != status) { /* * qcc:Event::Wait returned an error. This means the thread is stopping or was alerted * or the underlying platform-specific wait failed. In any case we'll just try again. */ QCC_LogError(status, ("Wait failed")); continue; } RequestThread* requestThread = new RequestThread(this, requestFd); status = requestThread->Start(NULL, this); if (ER_OK == status) { lock.Lock(); threads.push_back(requestThread); lock.Unlock(); } else { QCC_LogError(status, ("Start request thread failed")); delete requestThread; continue; } } QCC_DbgTrace(("%s exiting", __FUNCTION__)); qcc::Close(listenFd); return 0; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/CallbackNative.h0000644000175000017500000001063512620747066021624 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _CALLBACKNATIVE_H #define _CALLBACKNATIVE_H #include "AboutObjHost.h" #include "BusErrorHost.h" #include "InterfaceDescriptionNative.h" #include "MessageHost.h" #include "NativeObject.h" #include "PluginData.h" #include "ProxyBusObjectHost.h" #include "SessionOptsHost.h" #include "SocketFdHost.h" #include #include class CallbackNative : public NativeObject { public: CallbackNative(Plugin& plugin, NPObject* objectValue); virtual ~CallbackNative(); void onCallback(QStatus status); void onCallback(QStatus status, bool b); void onCallback(QStatus status, qcc::String& s); void onCallback(QStatus status, uint32_t u); void onCallback(QStatus status, ajn::SessionId id, SessionOptsHost& opts); void onCallback(QStatus status, ajn::SessionPort port); void onCallback(QStatus status, MessageHost& message, const ajn::MsgArg* args, size_t numArgs); void onCallback(QStatus status, AboutObjHost& aboutObj); void onCallback(QStatus status, ProxyBusObjectHost& proxyBusObject); void onCallback(QStatus status, SocketFdHost& socketFd); void onCallback(QStatus status, InterfaceDescriptionNative* interfaceDescription); void onCallback(QStatus status, InterfaceDescriptionNative** interfaceDescription, size_t numInterfaces); void onCallback(QStatus status, std::vector& children); void onCallback(BusErrorHost& busError); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, bool b); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, qcc::String& s); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, uint32_t u); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, ajn::SessionPort port); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, AboutObjHost& aboutObj); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, ProxyBusObjectHost& proxyBusObject); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, SocketFdHost& socketFd); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, InterfaceDescriptionNative* interfaceDescription); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, InterfaceDescriptionNative** interfaceDescription, size_t numInterfaces); static void DispatchCallback(Plugin& plugin, CallbackNative* callbackNative, QStatus status, std::vector& children); private: static void _StatusCallbackCB(PluginData::CallbackContext* ctx); static void _BoolCallbackCB(PluginData::CallbackContext* ctx); static void _StringCallbackCB(PluginData::CallbackContext* ctx); static void _UnsignedLongCallbackCB(PluginData::CallbackContext* ctx); static void _BindSessionPortCallbackCB(PluginData::CallbackContext* ctx); static void _GetAboutObjectCallbackCB(PluginData::CallbackContext* ctx); static void _GetProxyBusObjectCallbackCB(PluginData::CallbackContext* ctx); static void _GetSessionFdCallbackCB(PluginData::CallbackContext* ctx); static void _GetInterfaceCallbackCB(PluginData::CallbackContext* ctx); static void _GetInterfacesCallbackCB(PluginData::CallbackContext* ctx); static void _GetChildrenCallbackCB(PluginData::CallbackContext* ctx); }; #endif // _CALLBACKNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageHost.h0000644000175000017500000000344312620747066021202 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _MESSAGEHOST_H #define _MESSAGEHOST_H #include "BusAttachment.h" #include "ScriptableObject.h" #include #include #include class _MessageHost : public ScriptableObject { public: _MessageHost(Plugin& plugin, BusAttachment& busAttachment, ajn::Message& message); virtual ~_MessageHost(); protected: BusAttachment busAttachment; ajn::Message message; bool getSender(NPVariant* npresult); bool getDestination(NPVariant* npresult); bool getFlags(NPVariant* npresult); bool getInterfaceName(NPVariant* npresult); bool getObjectPath(NPVariant* npresult); bool getAuthMechanism(NPVariant* npresult); bool getIsUnreliable(NPVariant* npresult); bool getMemberName(NPVariant* npresult); bool getSignature(NPVariant* npresult); bool getSessionId(NPVariant* npresult); bool getTimestamp(NPVariant* npresult); }; typedef qcc::ManagedObj<_MessageHost> MessageHost; #endif // _MESSAGEHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/NativeObject.h0000644000175000017500000000250412620747066021332 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _NATIVEOBJECT_H #define _NATIVEOBJECT_H #include "Plugin.h" class NativeObject { public: /** * Retains a reference to an existing NPObject*. */ NativeObject(Plugin& plugin, NPObject* objectValue); /** * Creates a new NPObject* by calling "new Object();". */ NativeObject(Plugin& plugin); virtual ~NativeObject(); virtual void Invalidate(); bool operator==(const NativeObject& that) const; Plugin plugin; NPObject* objectValue; }; #endif // _NATIVEOBJECT_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/InterfaceDescriptionNative.h0000644000175000017500000000274312620747066024235 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _INTERFACEDESCRIPTIONNATIVE_H #define _INTERFACEDESCRIPTIONNATIVE_H #include "BusAttachment.h" #include "NativeObject.h" class InterfaceDescriptionNative : public NativeObject { public: static QStatus CreateInterface(Plugin& plugin, BusAttachment& busAttachment, InterfaceDescriptionNative* interfaceDescriptionNative); static InterfaceDescriptionNative* GetInterface(Plugin& plugin, BusAttachment& busAttachment, const qcc::String& name); InterfaceDescriptionNative(Plugin& plugin, NPObject* objectValue); InterfaceDescriptionNative(InterfaceDescriptionNative* other); virtual ~InterfaceDescriptionNative(); }; #endif // _INTERFACEDESCRIPTIONNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionOptsHost.cc0000644000175000017500000000371112620747066022243 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionOptsHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" _SessionOptsHost::_SessionOptsHost(Plugin& plugin, const ajn::SessionOpts& opts) : ScriptableObject(plugin, _SessionOptsInterface::Constants()), opts(opts) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("traffic", &_SessionOptsHost::getTraffic, 0); ATTRIBUTE("isMultipoint", &_SessionOptsHost::getIsMultipoint, 0); ATTRIBUTE("proximity", &_SessionOptsHost::getProximity, 0); ATTRIBUTE("transports", &_SessionOptsHost::getTransports, 0); } _SessionOptsHost::~_SessionOptsHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _SessionOptsHost::getTraffic(NPVariant* result) { ToOctet(plugin, opts.traffic, *result); return true; } bool _SessionOptsHost::getIsMultipoint(NPVariant* result) { ToBoolean(plugin, opts.isMultipoint, *result); return true; } bool _SessionOptsHost::getProximity(NPVariant* result) { ToOctet(plugin, opts.proximity, *result); return true; } bool _SessionOptsHost::getTransports(NPVariant* result) { ToUnsignedShort(plugin, opts.transports, *result); return true; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AboutObj.h0000644000175000017500000000174112620747066020464 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _ABOUTOBJ_H #define _ABOUTOBJ_H #include #include typedef qcc::ManagedObj AboutObj; #endif // _ABOUTOBJ_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AboutListenerNative.cc0000644000175000017500000000446112620747066023046 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "AboutListenerNative.h" #include "BusAttachmentHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" AboutListenerNative::AboutListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } AboutListenerNative::~AboutListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void AboutListenerNative::onAnnounced(const qcc::String& busName, uint16_t version, ajn::SessionPort port, const ajn::MsgArg& objectDescriptionArg, const ajn::MsgArg& aboutDataArg) { QCC_DbgTrace(("%s(busname=%s,version=%d,port=%d)", __FUNCTION__, busName.c_str(), version, port)); NPIdentifier onAnnounced = NPN_GetStringIdentifier("onAnnounced"); if (NPN_HasMethod(plugin->npp, objectValue, onAnnounced)) { NPVariant npargs[5]; ToDOMString(plugin, busName, npargs[0]); ToUnsignedShort(plugin, version, npargs[1]); ToUnsignedShort(plugin, port, npargs[2]); QStatus status = ER_OK; ToAny(plugin, objectDescriptionArg, npargs[3], status); assert(status == ER_OK); ToAny(plugin, aboutDataArg, npargs[4], status); assert(status == ER_OK); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onAnnounced, npargs, 5, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[4]); NPN_ReleaseVariantValue(&npargs[3]); NPN_ReleaseVariantValue(&npargs[0]); } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusAttachmentInterface.cc0000644000175000017500000000515412620747066023502 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "BusAttachmentInterface.h" #include "BusAttachmentHost.h" #include "CallbackNative.h" #include "FeaturePermissions.h" #include "HostObject.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _BusAttachmentInterface::constants; std::map& _BusAttachmentInterface::Constants() { if (constants.empty()) { CONSTANT("DBUS_NAME_FLAG_ALLOW_REPLACEMENT", 0x01); CONSTANT("DBUS_NAME_FLAG_REPLACE_EXISTING", 0x02); CONSTANT("DBUS_NAME_FLAG_DO_NOT_QUEUE", 0x04); CONSTANT("SESSION_PORT_ANY", 0); } return constants; } _BusAttachmentInterface::_BusAttachmentInterface(Plugin& plugin) : ScriptableObject(plugin, Constants()) { QCC_DbgTrace(("%s", __FUNCTION__)); } _BusAttachmentInterface::~_BusAttachmentInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _BusAttachmentInterface::Construct(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; int32_t level = 0; /* * Check permission level first. */ status = PluginData::PermissionLevel(plugin, ALLJOYN_FEATURE, level); if (ER_OK != status) { status = ER_OK; level = 0; } if (level <= 0) { typeError = true; plugin->RaiseTypeError("permission denied"); goto exit; } { BusAttachmentHost busAttachmentHost(plugin); ToHostObject(plugin, busAttachmentHost, *result); } exit: if ((ER_OK == status) && !typeError) { return true; } else { if (ER_OK != status) { plugin->RaiseBusError(status); } return false; } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/ScriptableObject.h0000644000175000017500000000774112620747066022204 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SCRIPTABLEOBJECT_H #define _SCRIPTABLEOBJECT_H #include "Plugin.h" #include class ScriptableObject { public: ScriptableObject(Plugin& plugin); ScriptableObject(Plugin& plugin, std::map& constants); virtual ~ScriptableObject(); virtual void Invalidate(); virtual bool HasMethod(const qcc::String& name); virtual bool Invoke(const qcc::String& name, const NPVariant* args, uint32_t argCount, NPVariant* result); virtual bool InvokeDefault(const NPVariant* args, uint32_t argCount, NPVariant* result); virtual bool HasProperty(const qcc::String& name); virtual bool GetProperty(const qcc::String& name, NPVariant* result); virtual bool SetProperty(const qcc::String& name, const NPVariant* value); virtual bool RemoveProperty(const qcc::String& name); virtual bool Enumerate(NPIdentifier** value, uint32_t* count); virtual bool Construct(const NPVariant* args, uint32_t argCount, NPVariant* result); protected: typedef bool (ScriptableObject::*Get)(NPVariant* result); typedef bool (ScriptableObject::*Set)(const NPVariant* value); class Attribute { public: Get get; Set set; Attribute(Get get, Set set = 0) : get(get), set(set) { } Attribute() : get(0), set(0) { } }; typedef bool (ScriptableObject::*Call)(const NPVariant* args, uint32_t argCount, NPVariant* result); class Operation { public: Call call; Operation(Call call) : call(call) { } Operation() : call(0) { } }; typedef bool (ScriptableObject::*Getter)(const qcc::String& name, NPVariant* result); typedef bool (ScriptableObject::*Setter)(const qcc::String& name, const NPVariant* value); typedef bool (ScriptableObject::*Deleter)(const qcc::String& name); typedef bool (ScriptableObject::*Enumerator)(NPIdentifier** value, uint32_t* count); typedef bool (ScriptableObject::*Caller)(const NPVariant* args, uint32_t argCount, NPVariant* result); Plugin plugin; std::map attributes; std::map operations; Getter getter; Setter setter; Deleter deleter; Enumerator enumerator; Caller caller; private: static std::map noConstants; std::map& constants; /* Constants are shared between interface and host objects */ }; #define CONSTANT(name, value) constants[name] = (value) #define ATTRIBUTE(name, get, set) attributes[name] = Attribute(static_cast(get), static_cast(set)) #define OPERATION(name, call) operations[name] = Operation(static_cast(call)) #define GETTER(customGetter) getter = static_cast(customGetter) #define SETTER(customSetter) setter = static_cast(customSetter) #define DELETER(customDeleter) deleter = static_cast(customDeleter) #define ENUMERATOR(customEnumerator) enumerator = static_cast(customEnumerator) #define CALLER(customCaller) caller = static_cast(customCaller) #define REMOVE_CONSTANT(name) constants.erase(name) #define REMOVE_ATTRIBUTE(name) attributes.erase(name) #define REMOVE_OPERATION(name) operations.erase(name) #endif // _SCRIPTABLEOBJECT_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusErrorHost.cc0000644000175000017500000000456412620747066021524 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "BusErrorHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" _BusErrorHost::_BusErrorHost(Plugin& plugin, const qcc::String& name, const qcc::String& message, QStatus code) : ScriptableObject(plugin, _BusErrorInterface::Constants()), name(name), message(message), code(code) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("name", &_BusErrorHost::getName, 0); ATTRIBUTE("message", &_BusErrorHost::getMessage, 0); ATTRIBUTE("code", &_BusErrorHost::getCode, 0); } _BusErrorHost::_BusErrorHost(Plugin& plugin, QStatus code) : ScriptableObject(plugin, _BusErrorInterface::Constants()), name("BusError"), code(code) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("name", &_BusErrorHost::getName, 0); ATTRIBUTE("message", &_BusErrorHost::getMessage, 0); ATTRIBUTE("code", &_BusErrorHost::getCode, 0); } _BusErrorHost::~_BusErrorHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } qcc::String _BusErrorHost::ToString() { qcc::String string; if (!name.empty()) { string += name + ": "; } if (!message.empty()) { string += message + " "; } string += qcc::String("(") + QCC_StatusText(code) + ")"; return string; } bool _BusErrorHost::getName(NPVariant* result) { ToDOMString(plugin, name, *result); return true; } bool _BusErrorHost::getMessage(NPVariant* result) { ToDOMString(plugin, message, *result); return true; } bool _BusErrorHost::getCode(NPVariant* result) { ToUnsignedShort(plugin, code, *result); return true; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/PluginData.h0000644000175000017500000000654012620747066021011 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _PLUGINDATA_H #define _PLUGINDATA_H #include "BusNamespace.h" #include "Plugin.h" #include #include #include #include #include #include class NativeObject; class PluginData { public: class CallbackContext { public: qcc::Event event; QStatus status; CallbackContext() : status(ER_ALERTED_THREAD) { } virtual ~CallbackContext() { } }; class _Callback { public: void (*callback)(CallbackContext*); CallbackContext* context; Plugin plugin; NPP npp; uintptr_t key; _Callback(Plugin& plugin, void(*callback)(CallbackContext*)); _Callback(); ~_Callback(); void SetEvent(); }; typedef qcc::ManagedObj<_Callback> Callback; static void DispatchCallback(Callback& callback); static void CancelCallback(Callback& callback); static bool StrictEquals(Plugin& plugin, const NPVariant& a, const NPVariant& b); static void DestroyOnMainThread(Plugin& plugin, PluginData::CallbackContext* context); static QStatus PermissionLevel(Plugin& plugin, const qcc::String& feature, int32_t& level); static QStatus SetPermissionLevel(Plugin& plugin, const qcc::String& feature, int32_t level, bool remember); /* * The static data relies on the library being unloaded (via NP_Shutdown) before NP_Initialize is * called again. That assumption is not true under Android. */ static void InitializeStaticData(); /* * For debugging purposes, a list of "alive" plugin-allocated NPObjects is stored. This lets me * see what NPObjects are still alive after NP_Shutdown (and thus will crash the process * containing the plugin when deallocate is called). */ static void InsertNPObject(NPObject* npobj); static void RemoveNPObject(NPObject* npobj); static void DumpNPObjects(); PluginData(Plugin& plugin); ~PluginData(); Plugin& GetPlugin(); NPObject* GetScriptableObject(); private: static qcc::Mutex lock; static std::list pendingCallbacks; static uintptr_t nextPendingCallbackKey; static void AsyncCall(void* key); static std::list npobjects; /** * Map of "org.alljoyn.bus" permission levels per security origin. * * The value is written to persistent storage if the user says to remember the setting. */ static std::map permissionLevels; Plugin plugin; BusNamespace busNamespace; }; #endif alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionMemberRemovedListenerNative.h0000644000175000017500000000247412620747066025735 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONMEMBERREMOVEDLISTENERNATIVE_H #define _SESSIONMEMBERREMOVEDLISTENERNATIVE_H #include "NativeObject.h" #include #include class SessionMemberRemovedListenerNative : public NativeObject { public: SessionMemberRemovedListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~SessionMemberRemovedListenerNative(); void onMemberRemoved(ajn::SessionId id, const qcc::String& uniqueName); }; #endif // _SESSIONMEMBERREMOVEDLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusAttachmentHost.h0000644000175000017500000001647012620747066022364 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSATTACHMENTHOST_H #define _BUSATTACHMENTHOST_H #include "BusAttachment.h" #include "ProxyBusObjectHost.h" #include "ScriptableObject.h" #include "AboutObjHost.h" #include #include class AboutListener; class AuthListener; class BusListener; class BusObjectListener; class InterfaceDescription; class SessionListener; class SessionPortListener; class SignalReceiver; class _BusAttachmentHost : public ScriptableObject { friend class JoinSessionAsyncCB; friend class SessionPortListener; public: _BusAttachmentHost(Plugin& plugin); virtual ~_BusAttachmentHost(); private: BusAttachment* busAttachment; AuthListener* authListener; AboutObjHost* aboutObj; qcc::String applicationName; std::list signalReceivers; std::list busListeners; std::list aboutListeners; std::map sessionPortListeners; std::map sessionListeners; std::map busObjectListeners; std::map proxyBusObjects; bool getGlobalGUIDString(NPVariant* result); bool getUniqueName(NPVariant* result); bool addLogonEntry(const NPVariant* args, uint32_t argCount, NPVariant* result); bool addMatch(const NPVariant* args, uint32_t argCount, NPVariant* result); bool advertiseName(const NPVariant* args, uint32_t argCount, NPVariant* result); bool bindSessionPort(const NPVariant* args, uint32_t argCount, NPVariant* result); bool cancelAdvertiseName(const NPVariant* args, uint32_t argCount, NPVariant* result); bool cancelFindAdvertisedName(const NPVariant* args, uint32_t argCount, NPVariant* result); bool cancelFindAdvertisedNameByTransport(const NPVariant* args, uint32_t argCount, NPVariant* result); bool cancelWhoImplements(const NPVariant* args, uint32_t argCount, NPVariant* result); bool clearKeyStore(const NPVariant* args, uint32_t argCount, NPVariant* result); bool clearKeys(const NPVariant* args, uint32_t argCount, NPVariant* result); bool connect(const NPVariant* args, uint32_t argCount, NPVariant* result); bool create(const NPVariant* args, uint32_t argCount, NPVariant* result); bool createInterface(const NPVariant* args, uint32_t argCount, NPVariant* result); bool createInterfacesFromXML(const NPVariant* args, uint32_t argCount, NPVariant* result); bool destroy(const NPVariant* args, uint32_t argCount, NPVariant* result); bool disconnect(const NPVariant* args, uint32_t argCount, NPVariant* result); bool enablePeerSecurity(const NPVariant* args, uint32_t argCount, NPVariant* result); bool findAdvertisedName(const NPVariant* args, uint32_t argCount, NPVariant* result); bool findAdvertisedNameByTransport(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getAboutObj(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getInterface(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getInterfaces(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getKeyExpiration(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getPeerGUID(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getPeerSecurityEnabled(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getProxyBusObject(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getTimestamp(const NPVariant* args, uint32_t argCount, NPVariant* result); bool joinSession(const NPVariant* args, uint32_t argCount, NPVariant* result); bool leaveSession(const NPVariant* args, uint32_t argCount, NPVariant* result); bool removeSessionMember(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getSessionFd(const NPVariant* args, uint32_t argCount, NPVariant* result); bool nameHasOwner(const NPVariant* args, uint32_t argCount, NPVariant* result); bool registerAboutListener(const NPVariant* args, uint32_t argCount, NPVariant* result); bool registerBusListener(const NPVariant* args, uint32_t argCount, NPVariant* result); bool registerBusObject(const NPVariant* args, uint32_t argCount, NPVariant* result); bool registerSignalHandler(const NPVariant* args, uint32_t argCount, NPVariant* result); bool releaseName(const NPVariant* args, uint32_t argCount, NPVariant* result); bool reloadKeyStore(const NPVariant* args, uint32_t argCount, NPVariant* result); bool removeMatch(const NPVariant* args, uint32_t argCount, NPVariant* result); bool requestName(const NPVariant* args, uint32_t argCount, NPVariant* result); bool setDaemonDebug(const NPVariant* args, uint32_t argCount, NPVariant* result); bool setLinkTimeout(const NPVariant* args, uint32_t argCount, NPVariant* result); bool setKeyExpiration(const NPVariant* args, uint32_t argCount, NPVariant* result); bool setSessionListener(const NPVariant* args, uint32_t argCount, NPVariant* result); bool unbindSessionPort(const NPVariant* args, uint32_t argCount, NPVariant* result); bool unregisterAboutListener(const NPVariant* args, uint32_t argCount, NPVariant* result); bool unregisterAllAboutListeners(const NPVariant* args, uint32_t argCount, NPVariant* result); bool unregisterBusListener(const NPVariant* args, uint32_t argCount, NPVariant* result); bool unregisterBusObject(const NPVariant* args, uint32_t argCount, NPVariant* result); bool unregisterSignalHandler(const NPVariant* args, uint32_t argCount, NPVariant* result); bool whoImplements(const NPVariant* args, uint32_t argCount, NPVariant* result); QStatus GetSignal(const qcc::String& signalName, const ajn::InterfaceDescription::Member*& signal); qcc::String MatchRule(const ajn::InterfaceDescription::Member* signal, const qcc::String& sourcePath); QStatus Connect(Plugin& plugin, const char* connectSpec); /** * Parse the ProxyBusObject name string into its components. * * @param[in] name a proxy bus object name of the form "" * @param[out] serviceName a D-Bus bus name * @param[out] path a D-Bus object path * @param[out] argMap a map of args from the args component of name: ":=[,=]" */ void ParseName(const qcc::String& name, qcc::String& serviceName, qcc::String& path, std::map& argMap); void stopAndJoin(); }; typedef qcc::ManagedObj<_BusAttachmentHost> BusAttachmentHost; #endif // _BUSATTACHMENTHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AboutListenerNative.h0000644000175000017500000000252412620747066022706 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _ABOUTLISTENERNATIVE_H #define _ABOUTLISTENERNATIVE_H #include "BusAttachmentHost.h" #include "NativeObject.h" #include #include class AboutListenerNative : public NativeObject { public: AboutListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~AboutListenerNative(); void onAnnounced(const qcc::String& busName, uint16_t version, ajn::SessionPort port, const ajn::MsgArg& objectDescriptionArg, const ajn::MsgArg& aboutDataArg); }; #endif // _ABOUTLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionJoinedListenerNative.cc0000644000175000017500000000342612620747066024550 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionJoinedListenerNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" SessionJoinedListenerNative::SessionJoinedListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } SessionJoinedListenerNative::~SessionJoinedListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void SessionJoinedListenerNative::onJoined(ajn::SessionPort sessionPort, ajn::SessionId id, const qcc::String& joiner) { QCC_DbgTrace(("%s(sessionPort=%d,id=%u,joiner=%s)", __FUNCTION__, sessionPort, id, joiner.c_str())); NPVariant npargs[3]; ToUnsignedShort(plugin, sessionPort, npargs[0]); ToUnsignedLong(plugin, id, npargs[1]); ToDOMString(plugin, joiner, npargs[2]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 3, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusAttachmentInterface.h0000644000175000017500000000262212620747066023341 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSATTACHMENTINTERFACE_H #define _BUSATTACHMENTINTERFACE_H #include "ScriptableObject.h" #include class _BusAttachmentInterface : public ScriptableObject { public: static std::map& Constants(); _BusAttachmentInterface(Plugin& plugin); virtual ~_BusAttachmentInterface(); virtual bool Construct(const NPVariant* args, uint32_t argCount, NPVariant* result); private: static std::map constants; }; typedef qcc::ManagedObj<_BusAttachmentInterface> BusAttachmentInterface; #endif // _BUSATTACHMENTINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusAttachmentHost.cc0000644000175000017500000046334012620747066022524 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "BusAttachmentHost.h" #include "AcceptSessionJoinerListenerNative.h" #include "AuthListenerNative.h" #include "AboutListenerNative.h" #include "BusListenerNative.h" #include "BusObject.h" #include "BusObjectNative.h" #include "CallbackNative.h" #include "InterfaceDescriptionNative.h" #include "MessageHost.h" #include "MessageListenerNative.h" #include "SessionJoinedListenerNative.h" #include "SessionLostListenerNative.h" #include "SessionMemberAddedListenerNative.h" #include "SessionMemberRemovedListenerNative.h" #include "SignalEmitterHost.h" #include "SocketFdHost.h" #include "Transport.h" #include "TypeMapping.h" #include #include #define QCC_MODULE "ALLJOYN_JS" class SignalReceiver : public ajn::MessageReceiver { public: class _Env { public: Plugin plugin; BusAttachment busAttachment; MessageListenerNative* signalListener; const ajn::InterfaceDescription::Member* signal; qcc::String sourcePath; _Env(Plugin& plugin, BusAttachment& busAttachment, MessageListenerNative* signalListener, const ajn::InterfaceDescription::Member* signal, qcc::String& sourcePath) : plugin(plugin), busAttachment(busAttachment), signalListener(signalListener), signal(signal), sourcePath(sourcePath) { QCC_DbgTrace(("%s this=%p", __FUNCTION__, this)); } ~_Env() { delete signalListener; } }; typedef qcc::ManagedObj<_Env> Env; Env env; SignalReceiver(Plugin& plugin, BusAttachment& busAttachment, MessageListenerNative* signalListener, const ajn::InterfaceDescription::Member* signal, qcc::String& sourcePath) : env(plugin, busAttachment, signalListener, signal, sourcePath) { QCC_DbgTrace(("%s this=%p", __FUNCTION__, this)); } virtual ~SignalReceiver() { QCC_DbgTrace(("%s this=%p", __FUNCTION__, this)); } class SignalHandlerContext : public PluginData::CallbackContext { public: Env env; const ajn::InterfaceDescription::Member* member; qcc::String sourcePath; ajn::Message message; SignalHandlerContext(Env& env, const ajn::InterfaceDescription::Member* member, const char* sourcePath, ajn::Message& message) : env(env), member(member), sourcePath(sourcePath), message(message) { } }; virtual void SignalHandler(const ajn::InterfaceDescription::Member* member, const char* sourcePath, ajn::Message& message) { PluginData::Callback callback(env->plugin, _SignalHandler); callback->context = new SignalHandlerContext(env, member, sourcePath, message); PluginData::DispatchCallback(callback); } static void _SignalHandler(PluginData::CallbackContext* ctx) { SignalHandlerContext* context = static_cast(ctx); MessageHost messageHost(context->env->plugin, context->env->busAttachment, context->message); size_t numArgs; const ajn::MsgArg* args; context->message->GetArgs(numArgs, args); context->env->signalListener->onMessage(messageHost, args, numArgs); } }; class AboutListener : public ajn::AboutListener { public: class _Env { public: Plugin plugin; _BusAttachmentHost* busAttachmentHost; BusAttachment busAttachment; AboutListenerNative* aboutListenerNative; _Env(Plugin& plugin, _BusAttachmentHost* busAttachmentHost, BusAttachment& busAttachment, AboutListenerNative* aboutListenerNative) : plugin(plugin), busAttachmentHost(busAttachmentHost), busAttachment(busAttachment), aboutListenerNative(aboutListenerNative) { } ~_Env() { delete aboutListenerNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; AboutListener(Plugin& plugin, _BusAttachmentHost* busAttachmentHost, BusAttachment& busAttachment, AboutListenerNative* aboutListenerNative) : env(plugin, busAttachmentHost, busAttachment, aboutListenerNative) { } virtual ~AboutListener() { } class AnnouncedContext : public PluginData::CallbackContext { public: Env env; qcc::String busName; uint16_t version; ajn::SessionPort port; ajn::MsgArg objectDescriptionArg; ajn::MsgArg aboutDataArg; AnnouncedContext(Env& env, const char* busName, uint16_t version, uint16_t port, ajn::MsgArg objectDescriptionArg, ajn::MsgArg aboutDataArg) : env(env), busName(busName), version(version), port(port), objectDescriptionArg(objectDescriptionArg), aboutDataArg(aboutDataArg) { } }; virtual void Announced(const char* busName, uint16_t version, ajn::SessionPort port, const ajn::MsgArg& objectDescriptionArg, const ajn::MsgArg& aboutDataArg) { PluginData::Callback callback(env->plugin, _Announced); callback->context = new AnnouncedContext(env, busName, version, port, objectDescriptionArg, aboutDataArg); PluginData::DispatchCallback(callback); } static void _Announced(PluginData::CallbackContext* ctx) { AnnouncedContext* context = static_cast(ctx); context->env->aboutListenerNative->onAnnounced(context->busName, context->version, context->port, context->objectDescriptionArg, context->aboutDataArg); } }; class BusListener : public ajn::BusListener { public: class _Env { public: Plugin plugin; /* * Use a naked pointer here instead of a ManagedObj since the lifetime of BusListener is tied * to the lifetime of the BusAttachmentHost. If we use a ManagedObj, then there is a circular * reference and the BusAttachmentHost may never be deleted. */ _BusAttachmentHost* busAttachmentHost; BusAttachment busAttachment; BusListenerNative* busListenerNative; _Env(Plugin& plugin, _BusAttachmentHost* busAttachmentHost, BusAttachment& busAttachment, BusListenerNative* busListenerNative) : plugin(plugin), busAttachmentHost(busAttachmentHost), busAttachment(busAttachment), busListenerNative(busListenerNative) { } ~_Env() { delete busListenerNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; BusListener(Plugin& plugin, _BusAttachmentHost* busAttachmentHost, BusAttachment& busAttachment, BusListenerNative* busListenerNative) : env(plugin, busAttachmentHost, busAttachment, busListenerNative) { } virtual ~BusListener() { } class ListenerRegisteredContext : public PluginData::CallbackContext { public: Env env; BusAttachmentHost busAttachmentHost; ListenerRegisteredContext(Env& env, BusAttachmentHost& busAttachmentHost) : env(env), busAttachmentHost(busAttachmentHost) { } }; virtual void ListenerRegistered(ajn::BusAttachment* bus) { QCC_UNUSED(bus); /* * Capture the naked pointer into a ManagedObj. This is safe to do here (and is necessary) since * this call will not occur without a valid BusAttachmentHost. The same cannot be said of the * dispatched callback below (_ListenerRegistered). */ BusAttachmentHost busAttachmentHost = BusAttachmentHost::wrap(env->busAttachmentHost); PluginData::Callback callback(env->plugin, _ListenerRegistered); callback->context = new ListenerRegisteredContext(env, busAttachmentHost); PluginData::DispatchCallback(callback); } static void _ListenerRegistered(PluginData::CallbackContext* ctx) { ListenerRegisteredContext* context = static_cast(ctx); context->env->busListenerNative->onRegistered(context->busAttachmentHost); } class ListenerUnregisteredContext : public PluginData::CallbackContext { public: Env env; ListenerUnregisteredContext(Env& env) : env(env) { } }; virtual void ListenerUnregistered() { PluginData::Callback callback(env->plugin, _ListenerUnregistered); callback->context = new ListenerUnregisteredContext(env); PluginData::DispatchCallback(callback); } static void _ListenerUnregistered(PluginData::CallbackContext* ctx) { ListenerUnregisteredContext* context = static_cast(ctx); context->env->busListenerNative->onUnregistered(); } class FoundAdvertisedNameContext : public PluginData::CallbackContext { public: Env env; qcc::String name; ajn::TransportMask transport; qcc::String namePrefix; FoundAdvertisedNameContext(Env& env, const char* name, ajn::TransportMask transport, const char* namePrefix) : env(env), name(name), transport(transport), namePrefix(namePrefix) { } }; virtual void FoundAdvertisedName(const char* name, ajn::TransportMask transport, const char* namePrefix) { PluginData::Callback callback(env->plugin, _FoundAdvertisedName); callback->context = new FoundAdvertisedNameContext(env, name, transport, namePrefix); PluginData::DispatchCallback(callback); } static void _FoundAdvertisedName(PluginData::CallbackContext* ctx) { FoundAdvertisedNameContext* context = static_cast(ctx); context->env->busListenerNative->onFoundAdvertisedName(context->name, context->transport, context->namePrefix); } class LostAdvertisedNameContext : public PluginData::CallbackContext { public: Env env; qcc::String name; ajn::TransportMask transport; qcc::String namePrefix; LostAdvertisedNameContext(Env& env, const char* name, ajn::TransportMask transport, const char* namePrefix) : env(env), name(name), transport(transport), namePrefix(namePrefix) { } }; virtual void LostAdvertisedName(const char* name, ajn::TransportMask transport, const char* namePrefix) { PluginData::Callback callback(env->plugin, _LostAdvertisedName); callback->context = new LostAdvertisedNameContext(env, name, transport, namePrefix); PluginData::DispatchCallback(callback); } static void _LostAdvertisedName(PluginData::CallbackContext* ctx) { LostAdvertisedNameContext* context = static_cast(ctx); context->env->busListenerNative->onLostAdvertisedName(context->name, context->transport, context->namePrefix); } class NameOwnerChangedContext : public PluginData::CallbackContext { public: Env env; qcc::String busName; qcc::String previousOwner; qcc::String newOwner; NameOwnerChangedContext(Env& env, const char* busName, const char* previousOwner, const char* newOwner) : env(env), busName(busName), previousOwner(previousOwner), newOwner(newOwner) { } }; virtual void NameOwnerChanged(const char* busName, const char* previousOwner, const char* newOwner) { PluginData::Callback callback(env->plugin, _NameOwnerChanged); callback->context = new NameOwnerChangedContext(env, busName, previousOwner, newOwner); PluginData::DispatchCallback(callback); } static void _NameOwnerChanged(PluginData::CallbackContext* ctx) { NameOwnerChangedContext* context = static_cast(ctx); context->env->busListenerNative->onNameOwnerChanged(context->busName, context->previousOwner, context->newOwner); } class PropertyChangedContext : public PluginData::CallbackContext { public: Env env; const qcc::String propName; const ajn::MsgArg* propValue; PropertyChangedContext(Env& env, const char* propName, const ajn::MsgArg* propValue) : env(env), propName(propName), propValue(propValue) { } }; virtual void PropertyChanged(const char* propName, const ajn::MsgArg* propValue) { PluginData::Callback callback(env->plugin, _PropertyChanged); callback->context = new PropertyChangedContext(env, propName, propValue); PluginData::DispatchCallback(callback); } static void _PropertyChanged(PluginData::CallbackContext* ctx) { PropertyChangedContext* context = static_cast(ctx); context->env->busListenerNative->onPropertyChanged(context->propName, context->propValue); } class BusStoppingContext : public PluginData::CallbackContext { public: Env env; BusStoppingContext(Env& env) : env(env) { } }; virtual void BusStopping() { PluginData::Callback callback(env->plugin, _BusStopping); callback->context = new BusStoppingContext(env); PluginData::DispatchCallback(callback); } static void _BusStopping(PluginData::CallbackContext* ctx) { BusStoppingContext* context = static_cast(ctx); context->env->busListenerNative->onStopping(); } class BusDisconnectedContext : public PluginData::CallbackContext { public: Env env; BusDisconnectedContext(Env& env) : env(env) { } }; virtual void BusDisconnected() { PluginData::Callback callback(env->plugin, _BusDisconnected); callback->context = new BusDisconnectedContext(env); PluginData::DispatchCallback(callback); } static void _BusDisconnected(PluginData::CallbackContext* ctx) { BusDisconnectedContext* context = static_cast(ctx); context->env->busListenerNative->onDisconnected(); } }; class SessionListener : public ajn::SessionListener { public: class _Env { public: Plugin plugin; BusAttachment busAttachment; SessionLostListenerNative* sessionLostListenerNative; SessionMemberAddedListenerNative* sessionMemberAddedListenerNative; SessionMemberRemovedListenerNative* sessionMemberRemovedListenerNative; _Env(Plugin& plugin, BusAttachment& busAttachment, SessionLostListenerNative* sessionLostListenerNative, SessionMemberAddedListenerNative* sessionMemberAddedListenerNative, SessionMemberRemovedListenerNative* sessionMemberRemovedListenerNative) : plugin(plugin), busAttachment(busAttachment), sessionLostListenerNative(sessionLostListenerNative), sessionMemberAddedListenerNative(sessionMemberAddedListenerNative), sessionMemberRemovedListenerNative(sessionMemberRemovedListenerNative) { } _Env(Plugin& plugin, BusAttachment& busAttachment) : plugin(plugin), busAttachment(busAttachment), sessionLostListenerNative(NULL), sessionMemberAddedListenerNative(NULL), sessionMemberRemovedListenerNative(NULL) { } ~_Env() { delete sessionLostListenerNative; delete sessionMemberAddedListenerNative; delete sessionMemberRemovedListenerNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; SessionListener(Plugin& plugin, BusAttachment& busAttachment, SessionLostListenerNative* sessionLostListenerNative, SessionMemberAddedListenerNative* sessionMemberAddedListenerNative, SessionMemberRemovedListenerNative* sessionMemberRemovedListenerNative) : env(plugin, busAttachment, sessionLostListenerNative, sessionMemberAddedListenerNative, sessionMemberRemovedListenerNative) { } SessionListener(Plugin& plugin, BusAttachment& busAttachment, Env& env) : env(env) { QCC_UNUSED(plugin); QCC_UNUSED(busAttachment); QCC_UNUSED(env); } SessionListener(Plugin& plugin, BusAttachment& busAttachment) : env(plugin, busAttachment) { } virtual ~SessionListener() { } class SessionLostContext : public PluginData::CallbackContext { public: Env env; ajn::SessionId id; ajn::SessionListener::SessionLostReason reason; SessionLostContext(Env& env, ajn::SessionId id, ajn::SessionListener::SessionLostReason reason) : env(env), id(id), reason(reason) { } }; virtual void SessionLost(ajn::SessionId id, ajn::SessionListener::SessionLostReason reason) { PluginData::Callback callback(env->plugin, _SessionLost); callback->context = new SessionLostContext(env, id, reason); PluginData::DispatchCallback(callback); } static void _SessionLost(PluginData::CallbackContext* ctx) { SessionLostContext* context = static_cast(ctx); if (context->env->sessionLostListenerNative) { context->env->sessionLostListenerNative->onLost(context->id, context->reason); } } class SessionMemberAddedContext : public PluginData::CallbackContext { public: Env env; ajn::SessionId id; qcc::String uniqueName; SessionMemberAddedContext(Env& env, ajn::SessionId id, const char* uniqueName) : env(env), id(id), uniqueName(uniqueName) { } }; virtual void SessionMemberAdded(ajn::SessionId id, const char* uniqueName) { PluginData::Callback callback(env->plugin, _SessionMemberAdded); callback->context = new SessionMemberAddedContext(env, id, uniqueName); PluginData::DispatchCallback(callback); } static void _SessionMemberAdded(PluginData::CallbackContext* ctx) { SessionMemberAddedContext* context = static_cast(ctx); if (context->env->sessionMemberAddedListenerNative) { context->env->sessionMemberAddedListenerNative->onMemberAdded(context->id, context->uniqueName); } } class SessionMemberRemovedContext : public PluginData::CallbackContext { public: Env env; ajn::SessionId id; qcc::String uniqueName; SessionMemberRemovedContext(Env& env, ajn::SessionId id, const char* uniqueName) : env(env), id(id), uniqueName(uniqueName) { } }; virtual void SessionMemberRemoved(ajn::SessionId id, const char* uniqueName) { PluginData::Callback callback(env->plugin, _SessionMemberRemoved); callback->context = new SessionMemberRemovedContext(env, id, uniqueName); PluginData::DispatchCallback(callback); } static void _SessionMemberRemoved(PluginData::CallbackContext* ctx) { SessionMemberRemovedContext* context = static_cast(ctx); if (context->env->sessionMemberRemovedListenerNative) { context->env->sessionMemberRemovedListenerNative->onMemberRemoved(context->id, context->uniqueName); } } }; class SessionPortListener : public ajn::SessionPortListener { public: class _Env { public: Plugin plugin; /* * Use a naked pointer here instead of a ManagedObj since the lifetime of SessionPortListener is tied * to the lifetime of the BusAttachmentHost. If we use a ManagedObj, then there is a circular * reference and the BusAttachmentHost may never be deleted. */ _BusAttachmentHost* busAttachmentHost; BusAttachment busAttachment; AcceptSessionJoinerListenerNative* acceptSessionListenerNative; SessionJoinedListenerNative* sessionJoinedListenerNative; SessionListener::Env sessionListenerEnv; _Env(Plugin& plugin, _BusAttachmentHost* busAttachmentHost, BusAttachment& busAttachment, AcceptSessionJoinerListenerNative* acceptSessionListenerNative, SessionJoinedListenerNative* sessionJoinedListenerNative, SessionListener::Env sessionListenerEnv) : plugin(plugin), busAttachmentHost(busAttachmentHost), busAttachment(busAttachment), acceptSessionListenerNative(acceptSessionListenerNative), sessionJoinedListenerNative(sessionJoinedListenerNative), sessionListenerEnv(sessionListenerEnv) { } ~_Env() { delete sessionJoinedListenerNative; delete acceptSessionListenerNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; qcc::Event cancelEvent; SessionPortListener(Plugin& plugin, _BusAttachmentHost* busAttachmentHost, BusAttachment& busAttachment, AcceptSessionJoinerListenerNative* acceptSessionListenerNative, SessionJoinedListenerNative* sessionJoinedListenerNative, SessionListener::Env sessionListenerEnv) : env(plugin, busAttachmentHost, busAttachment, acceptSessionListenerNative, sessionJoinedListenerNative, sessionListenerEnv) { } virtual ~SessionPortListener() { } class AcceptSessionJoinerContext : public PluginData::CallbackContext { public: Env env; ajn::SessionPort sessionPort; qcc::String joiner; const ajn::SessionOpts opts; AcceptSessionJoinerContext(Env& env, ajn::SessionPort sessionPort, const char* joiner, const ajn::SessionOpts& opts) : env(env), sessionPort(sessionPort), joiner(joiner), opts(opts) { } }; virtual bool AcceptSessionJoiner(ajn::SessionPort sessionPort, const char* joiner, const ajn::SessionOpts& opts) { PluginData::Callback callback(env->plugin, _AcceptSessionJoiner); callback->context = new AcceptSessionJoinerContext(env, sessionPort, joiner, opts); PluginData::DispatchCallback(callback); /* * Complex processing here to prevent UI thread from deadlocking if it ends up calling * unbindSessionPort. * * UnbindSessionPort() will block until all AcceptSessionJoiner callbacks have returned. * Setting the cancelEvent will unblock any synchronous callback. Then a little extra * coordination is needed to remove the dispatch context so that when the dispatched callback * is run it does nothing. */ std::vector check; check.push_back(&callback->context->event); check.push_back(&cancelEvent); std::vector signaled; signaled.clear(); env->busAttachment->EnableConcurrentCallbacks(); QStatus status = qcc::Event::Wait(check, signaled); assert(ER_OK == status); if (ER_OK != status) { QCC_LogError(status, ("Wait failed")); } for (std::vector::iterator i = signaled.begin(); i != signaled.end(); ++i) { if (*i == &cancelEvent) { PluginData::CancelCallback(callback); callback->context->status = ER_ALERTED_THREAD; break; } } return (ER_OK == callback->context->status); } static void _AcceptSessionJoiner(PluginData::CallbackContext* ctx) { AcceptSessionJoinerContext* context = static_cast(ctx); if (context->env->acceptSessionListenerNative) { SessionOptsHost optsHost(context->env->plugin, context->opts); bool accepted = context->env->acceptSessionListenerNative->onAccept(context->sessionPort, context->joiner, optsHost); context->status = accepted ? ER_OK : ER_FAIL; } else { context->status = ER_FAIL; } } class SessionJoinedContext : public PluginData::CallbackContext { public: Env env; BusAttachmentHost busAttachmentHost; ajn::SessionPort sessionPort; ajn::SessionId id; qcc::String joiner; SessionListener* sessionListener; SessionJoinedContext(Env& env, BusAttachmentHost& busAttachmentHost, ajn::SessionPort sessionPort, ajn::SessionId id, const char* joiner, SessionListener* sessionListener) : env(env), busAttachmentHost(busAttachmentHost), sessionPort(sessionPort), id(id), joiner(joiner), sessionListener(sessionListener) { } virtual ~SessionJoinedContext() { } }; virtual void SessionJoined(ajn::SessionPort sessionPort, ajn::SessionId id, const char* joiner) { SessionListener* sessionListener = NULL; /* * We have to do this here, otherwise we can miss the session member added callback (the app won't have called * setSessionListener soon enough). */ if (env->sessionListenerEnv->sessionLostListenerNative || env->sessionListenerEnv->sessionMemberAddedListenerNative || env->sessionListenerEnv->sessionMemberRemovedListenerNative) { sessionListener = new SessionListener(env->plugin, env->busAttachment, env->sessionListenerEnv); QStatus status = env->busAttachment->SetSessionListener(id, sessionListener); if (status != ER_OK) { QCC_LogError(status, ("SetSessionListener failed")); delete sessionListener; } } /* * Capture the naked pointer into a ManagedObj. This is safe to do here (and is necessary) since * this call will not occur without a valid BusAttachmentHost. The same cannot be said of the * dispatched callback below (_SessionJoined). */ BusAttachmentHost busAttachmentHost = BusAttachmentHost::wrap(env->busAttachmentHost); PluginData::Callback callback(env->plugin, _SessionJoined); callback->context = new SessionJoinedContext(env, busAttachmentHost, sessionPort, id, joiner, sessionListener); PluginData::DispatchCallback(callback); } static void _SessionJoined(PluginData::CallbackContext* ctx) { SessionJoinedContext* context = static_cast(ctx); if (context->sessionListener) { std::pair element(context->id, context->sessionListener); context->busAttachmentHost->sessionListeners.insert(element); } if (context->env->sessionJoinedListenerNative) { context->env->sessionJoinedListenerNative->onJoined(context->sessionPort, context->id, context->joiner); } } }; class JoinSessionAsyncCB : public ajn::BusAttachment::JoinSessionAsyncCB { public: class _Env { public: Plugin plugin; BusAttachmentHost busAttachmentHost; BusAttachment busAttachment; CallbackNative* callbackNative; SessionListener* sessionListener; QStatus status; _Env(Plugin& plugin, BusAttachmentHost& busAttachmentHost, BusAttachment& busAttachment, CallbackNative* callbackNative, SessionListener* sessionListener) : plugin(plugin), busAttachmentHost(busAttachmentHost), busAttachment(busAttachment), callbackNative(callbackNative), sessionListener(sessionListener) { } ~_Env() { delete sessionListener; if (callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } } }; typedef qcc::ManagedObj<_Env> Env; Env env; JoinSessionAsyncCB(Plugin& plugin, BusAttachmentHost& busAttachmentHost, BusAttachment& busAttachment, CallbackNative* callbackNative, SessionListener* sessionListener) : env(plugin, busAttachmentHost, busAttachment, callbackNative, sessionListener) { } virtual ~JoinSessionAsyncCB() { } class JoinSessionCBContext : public PluginData::CallbackContext { public: Env env; QStatus status; ajn::SessionId sessionId; ajn::SessionOpts sessionOpts; JoinSessionCBContext(Env& env, QStatus status, ajn::SessionId sessionId, ajn::SessionOpts sessionOpts) : env(env), status(status), sessionId(sessionId), sessionOpts(sessionOpts) { } }; virtual void JoinSessionCB(QStatus status, ajn::SessionId sessionId, const ajn::SessionOpts& opts, void*) { Plugin plugin = env->plugin; PluginData::Callback callback(env->plugin, _JoinSessionCB); callback->context = new JoinSessionCBContext(env, status, sessionId, opts); delete this; PluginData::DispatchCallback(callback); } static void _JoinSessionCB(PluginData::CallbackContext* ctx) { JoinSessionCBContext* context = static_cast(ctx); if (ER_OK == context->status) { context->env->busAttachment->SetSessionListener(context->sessionId, context->env->sessionListener); std::pair element(context->sessionId, context->env->sessionListener); context->env->busAttachmentHost->sessionListeners.insert(element); context->env->sessionListener = NULL; /* sessionListeners now owns sessionListener */ SessionOptsHost sessionOpts(context->env->plugin, context->sessionOpts); context->env->callbackNative->onCallback(context->status, context->sessionId, sessionOpts); } else { BusErrorHost busError(context->env->plugin, context->status); context->env->callbackNative->onCallback(busError); } delete context->env->callbackNative; context->env->callbackNative = NULL; } }; class BusObjectListener : public _BusObjectListener { public: class _Env { public: Plugin plugin; BusAttachment busAttachment; BusObject busObject; BusObjectNative* busObjectNative; _Env(Plugin& plugin, BusAttachment& busAttachment, const char* path, BusObjectNative* busObjectNative) : plugin(plugin), busAttachment(busAttachment), busObject(busAttachment, path), busObjectNative(busObjectNative) { } ~_Env() { delete busObjectNative; } }; typedef qcc::ManagedObj<_Env> Env; mutable Env env; /* mutable so that GenerateIntrospection can be declared const to match ajn::BusObject */ BusObjectListener(Plugin& plugin, BusAttachment& busAttachment, const char* path, BusObjectNative* busObjectNative) : env(plugin, busAttachment, path, busObjectNative) { env->busObject->SetBusObjectListener(this); } virtual ~BusObjectListener() { env->busObject->SetBusObjectListener(0); } QStatus AddInterfaceAndMethodHandlers(const ajn::BusObject::AnnounceFlag isAnnounced) { QStatus status = ER_OK; bool hasSignal = false; NPIdentifier* properties = NULL; uint32_t propertiesCount = 0; if (NPN_Enumerate(env->plugin->npp, env->busObjectNative->objectValue, &properties, &propertiesCount)) { for (uint32_t i = 0; (ER_OK == status) && (i < propertiesCount); ++i) { if (!NPN_IdentifierIsString(properties[i])) { continue; } NPUTF8* property = NPN_UTF8FromIdentifier(properties[i]); if (!property) { status = ER_OUT_OF_MEMORY; break; } const ajn::InterfaceDescription* interface = env->busAttachment->GetInterface(property); if (!interface) { QCC_DbgHLPrintf(("No such interface '%s', ignoring", property)); } NPN_MemFree(property); if (!interface) { continue; } QCC_DbgTrace(("Adding '%s'", interface->GetName())); status = env->busObject->AddInterface(*interface, isAnnounced); if (ER_OK != status) { QCC_LogError(status, ("AddInterface failed")); break; } size_t numMembers = interface->GetMembers(); if (!numMembers) { continue; } const ajn::InterfaceDescription::Member** members = new const ajn::InterfaceDescription::Member*[numMembers]; interface->GetMembers(members, numMembers); for (size_t j = 0; (ER_OK == status) && (j < numMembers); ++j) { if (ajn::MESSAGE_METHOD_CALL == members[j]->memberType) { status = env->busObject->AddMethodHandler(members[j]); } else if (ajn::MESSAGE_SIGNAL == members[j]->memberType) { hasSignal = true; } } delete[] members; } NPN_MemFree(properties); } if (hasSignal) { SignalEmitterHost emitter(env->plugin, env->busObject); NPVariant npemitter; ToHostObject(env->plugin, emitter, npemitter); if (!NPN_SetProperty(env->plugin->npp, env->busObjectNative->objectValue, NPN_GetStringIdentifier("signal"), &npemitter)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&npemitter); } return status; } class MethodHandlerContext : public PluginData::CallbackContext { public: Env env; const ajn::InterfaceDescription::Member* member; ajn::Message message; MethodHandlerContext(Env& env, const ajn::InterfaceDescription::Member* member, ajn::Message& message) : env(env), member(member), message(message) { } }; void MethodHandler(const ajn::InterfaceDescription::Member* member, ajn::Message& message) { PluginData::Callback callback(env->plugin, _MethodHandler); callback->context = new MethodHandlerContext(env, member, message); PluginData::DispatchCallback(callback); } static void _MethodHandler(PluginData::CallbackContext* ctx) { MethodHandlerContext* context = static_cast(ctx); MessageReplyHost messageReplyHost(context->env->plugin, context->env->busAttachment, context->env->busObject, context->message, context->member->returnSignature); size_t numArgs; const ajn::MsgArg* args; context->message->GetArgs(numArgs, args); context->env->busObjectNative->onMessage(context->member->iface->GetName(), context->member->name.c_str(), messageReplyHost, args, numArgs); } class ObjectRegisteredContext : public PluginData::CallbackContext { public: Env env; ObjectRegisteredContext(Env& env) : env(env) { } }; virtual void ObjectRegistered() { PluginData::Callback callback(env->plugin, _ObjectRegistered); callback->context = new ObjectRegisteredContext(env); PluginData::DispatchCallback(callback); } static void _ObjectRegistered(PluginData::CallbackContext* ctx) { ObjectRegisteredContext* context = static_cast(ctx); context->env->busObjectNative->onRegistered(); } class ObjectUnregisteredContext : public PluginData::CallbackContext { public: Env env; ObjectUnregisteredContext(Env& env) : env(env) { } }; virtual void ObjectUnregistered() { PluginData::Callback callback(env->plugin, _ObjectUnregistered); callback->context = new ObjectUnregisteredContext(env); PluginData::DispatchCallback(callback); } static void _ObjectUnregistered(PluginData::CallbackContext* ctx) { ObjectUnregisteredContext* context = static_cast(ctx); context->env->busObjectNative->onUnregistered(); } class GetContext : public PluginData::CallbackContext { public: Env env; qcc::String ifcName; qcc::String propName; ajn::MsgArg val; GetContext(Env& env, const char* ifcName, const char* propName, ajn::MsgArg& val) : env(env), ifcName(ifcName), propName(propName), val(val) { } }; virtual QStatus Get(const char* ifcName, const char* propName, ajn::MsgArg& val) { PluginData::Callback callback(env->plugin, _Get); callback->context = new GetContext(env, ifcName, propName, val); PluginData::DispatchCallback(callback); env->busAttachment->EnableConcurrentCallbacks(); qcc::Event::Wait(callback->context->event); val = static_cast(callback->context)->val; return callback->context->status; } static void _Get(PluginData::CallbackContext* ctx) { GetContext* context = static_cast(ctx); const ajn::InterfaceDescription* interface = context->env->busAttachment->GetInterface(context->ifcName.c_str()); if (!interface) { context->status = ER_BUS_NO_SUCH_INTERFACE; return; } const ajn::InterfaceDescription::Property* property = interface->GetProperty(context->propName.c_str()); if (!property) { context->status = ER_BUS_NO_SUCH_PROPERTY; return; } context->status = context->env->busObjectNative->get(interface, property, context->val); } class SetContext : public PluginData::CallbackContext { public: Env env; qcc::String ifcName; qcc::String propName; ajn::MsgArg val; SetContext(Env& env, const char* ifcName, const char* propName, ajn::MsgArg& val) : env(env), ifcName(ifcName), propName(propName), val(val) { } }; virtual QStatus Set(const char* ifcName, const char* propName, ajn::MsgArg& val) { PluginData::Callback callback(env->plugin, _Set); callback->context = new SetContext(env, ifcName, propName, val); PluginData::DispatchCallback(callback); env->busAttachment->EnableConcurrentCallbacks(); qcc::Event::Wait(callback->context->event); return callback->context->status; } static void _Set(PluginData::CallbackContext* ctx) { SetContext* context = static_cast(ctx); const ajn::InterfaceDescription* interface = context->env->busAttachment->GetInterface(context->ifcName.c_str()); if (!interface) { context->status = ER_BUS_NO_SUCH_INTERFACE; return; } const ajn::InterfaceDescription::Property* property = interface->GetProperty(context->propName.c_str()); if (!property) { context->status = ER_BUS_NO_SUCH_PROPERTY; return; } context->status = context->env->busObjectNative->set(interface, property, context->val); } class GenerateIntrospectionContext : public PluginData::CallbackContext { public: Env env; bool deep; size_t indent; qcc::String introspection; GenerateIntrospectionContext(Env& env, bool deep, size_t indent, qcc::String& introspection) : env(env), deep(deep), indent(indent), introspection(introspection) { } }; virtual QStatus GenerateIntrospection(bool deep, size_t indent, qcc::String& introspection) const { PluginData::Callback callback(env->plugin, _GenerateIntrospection); callback->context = new GenerateIntrospectionContext(env, deep, indent, introspection); PluginData::DispatchCallback(callback); env->busAttachment->EnableConcurrentCallbacks(); qcc::Event::Wait(callback->context->event); introspection = static_cast(callback->context)->introspection; return callback->context->status; } static void _GenerateIntrospection(PluginData::CallbackContext* ctx) { GenerateIntrospectionContext* context = static_cast(ctx); context->status = context->env->busObjectNative->toXML(context->deep, context->indent, context->introspection); } }; class AuthListener : public ajn::AuthListener { public: class _Env { public: Plugin plugin; BusAttachment busAttachment; qcc::String authMechanisms; AuthListenerNative* authListenerNative; _Env(Plugin& plugin, BusAttachment& busAttachment, qcc::String& authMechanisms, AuthListenerNative* authListenerNative) : plugin(plugin), busAttachment(busAttachment), authMechanisms(authMechanisms), authListenerNative(authListenerNative) { } ~_Env() { delete authListenerNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; qcc::Event cancelEvent; AuthListener(Plugin& plugin, BusAttachment& busAttachment, qcc::String& authMechanisms, AuthListenerNative* authListenerNative) : env(plugin, busAttachment, authMechanisms, authListenerNative) { QCC_DbgTrace(("AuthListener %p", this)); } virtual ~AuthListener() { QCC_DbgTrace(("~AuthListener %p", this)); } class RequestCredentialsContext : public PluginData::CallbackContext { public: Env env; qcc::String authMechanism; qcc::String peerName; uint16_t authCount; qcc::String userName; uint16_t credMask; Credentials credentials; RequestCredentialsContext(Env& env, const char* authMechanism, const char* peerName, uint16_t authCount, const char* userName, uint16_t credMask, Credentials& credentials) : env(env), authMechanism(authMechanism), peerName(peerName), authCount(authCount), userName(userName), credMask(credMask), credentials(credentials) { } }; virtual bool RequestCredentials(const char* authMechanism, const char* peerName, uint16_t authCount, const char* userName, uint16_t credMask, Credentials& credentials) { QCC_DbgTrace(("%s(authMechanism=%s,peerName=%s,authCount=%u,userName=%s,credMask=0x%04x)", __FUNCTION__, authMechanism, peerName, authCount, userName, credMask)); PluginData::Callback callback(env->plugin, _RequestCredentials); callback->context = new RequestCredentialsContext(env, authMechanism, peerName, authCount, userName, credMask, credentials); PluginData::DispatchCallback(callback); /* * Complex processing here to prevent UI thread from deadlocking if _BusAttachmentHost * destructor is called. * * EnablePeerSecurity(0, ...), called from the _BusAttachmentHost destructor, will block * until all AuthListener callbacks have returned. Setting the cancelEvent will unblock any * synchronous callback. Then a little extra coordination is needed to remove the dispatch * context so that when the dispatched callback is run it does nothing. */ std::vector check; check.push_back(&callback->context->event); check.push_back(&cancelEvent); std::vector signaled; signaled.clear(); env->busAttachment->EnableConcurrentCallbacks(); QStatus status = qcc::Event::Wait(check, signaled); assert(ER_OK == status); if (ER_OK != status) { QCC_LogError(status, ("Wait failed")); } for (std::vector::iterator i = signaled.begin(); i != signaled.end(); ++i) { if (*i == &cancelEvent) { PluginData::CancelCallback(callback); callback->context->status = ER_ALERTED_THREAD; break; } } credentials = static_cast(callback->context)->credentials; return (ER_OK == callback->context->status); } static void _RequestCredentials(PluginData::CallbackContext* ctx) { RequestCredentialsContext* context = static_cast(ctx); if (context->env->authListenerNative) { CredentialsHost credentialsHost(context->env->plugin, context->credentials); bool requested = context->env->authListenerNative->onRequest(context->authMechanism, context->peerName, context->authCount, context->userName, context->credMask, credentialsHost); context->status = requested ? ER_OK : ER_FAIL; } else { context->status = ER_FAIL; } } class VerifyCredentialsContext : public PluginData::CallbackContext { public: Env env; qcc::String authMechanism; qcc::String peerName; Credentials credentials; VerifyCredentialsContext(Env& env, const char* authMechanism, const char* peerName, const Credentials& credentials) : env(env), authMechanism(authMechanism), peerName(peerName), credentials(credentials) { } }; virtual bool VerifyCredentials(const char* authMechanism, const char* peerName, const Credentials& credentials) { QCC_DbgTrace(("%s(authMechanism=%s,peerName=%s)", __FUNCTION__, authMechanism, peerName)); PluginData::Callback callback(env->plugin, _VerifyCredentials); callback->context = new VerifyCredentialsContext(env, authMechanism, peerName, credentials); PluginData::DispatchCallback(callback); std::vector check; check.push_back(&callback->context->event); check.push_back(&cancelEvent); std::vector signaled; signaled.clear(); env->busAttachment->EnableConcurrentCallbacks(); QStatus status = qcc::Event::Wait(check, signaled); assert(ER_OK == status); if (ER_OK != status) { QCC_LogError(status, ("Wait failed")); } for (std::vector::iterator i = signaled.begin(); i != signaled.end(); ++i) { if (*i == &cancelEvent) { PluginData::CancelCallback(callback); callback->context->status = ER_ALERTED_THREAD; break; } } return (ER_OK == callback->context->status); } static void _VerifyCredentials(PluginData::CallbackContext* ctx) { VerifyCredentialsContext* context = static_cast(ctx); if (context->env->authListenerNative) { CredentialsHost credentialsHost(context->env->plugin, context->credentials); bool verified = context->env->authListenerNative->onVerify(context->authMechanism, context->peerName, credentialsHost); context->status = verified ? ER_OK : ER_FAIL; } else { context->status = ER_FAIL; } } class SecurityViolationContext : public PluginData::CallbackContext { public: Env env; QStatus violation; ajn::Message message; SecurityViolationContext(Env& env, QStatus violation, const ajn::Message& message) : env(env), violation(violation), message(message) { } }; virtual void SecurityViolation(QStatus status, const ajn::Message& message) { QCC_DbgTrace(("%s(status=%s,msg=%s)", __FUNCTION__, QCC_StatusText(status), message->ToString().c_str())); PluginData::Callback callback(env->plugin, _SecurityViolation); callback->context = new SecurityViolationContext(env, status, message); PluginData::DispatchCallback(callback); } static void _SecurityViolation(PluginData::CallbackContext* ctx) { SecurityViolationContext* context = static_cast(ctx); if (context->env->authListenerNative) { MessageHost messageHost(context->env->plugin, context->env->busAttachment, context->message); context->env->authListenerNative->onSecurityViolation(context->violation, messageHost); } } class AuthenticationCompleteContext : public PluginData::CallbackContext { public: Env env; qcc::String authMechanism; qcc::String peerName; bool success; AuthenticationCompleteContext(Env& env, const char* authMechanism, const char* peerName, bool success) : env(env), authMechanism(authMechanism), peerName(peerName), success(success) { } }; virtual void AuthenticationComplete(const char* authMechanism, const char* peerName, bool success) { QCC_DbgTrace(("%s(authMechanism=%s,peerName=%s,success=%d)", __FUNCTION__, authMechanism, peerName, success)); PluginData::Callback callback(env->plugin, _AuthenticationComplete); callback->context = new AuthenticationCompleteContext(env, authMechanism, peerName, success); PluginData::DispatchCallback(callback); } static void _AuthenticationComplete(PluginData::CallbackContext* ctx) { AuthenticationCompleteContext* context = static_cast(ctx); if (context->env->authListenerNative) { context->env->authListenerNative->onComplete(context->authMechanism, context->peerName, context->success); } } }; _BusAttachmentHost::_BusAttachmentHost(Plugin& plugin) : ScriptableObject(plugin, _BusAttachmentInterface::Constants()), busAttachment(0), authListener(0), aboutObj(0) { QCC_DbgTrace(("%s %p", __FUNCTION__, this)); OPERATION("create", &_BusAttachmentHost::create); OPERATION("destroy", &_BusAttachmentHost::destroy); } _BusAttachmentHost::~_BusAttachmentHost() { QCC_DbgTrace(("%s %p", __FUNCTION__, this)); stopAndJoin(); } bool _BusAttachmentHost::getUniqueName(NPVariant* result) { ToDOMString(plugin, (*busAttachment)->GetUniqueName(), *result, TreatEmptyStringAsNull); return true; } bool _BusAttachmentHost::getGlobalGUIDString(NPVariant* result) { ToDOMString(plugin, (*busAttachment)->GetGlobalGUIDString(), *result); return true; } bool _BusAttachmentHost::getTimestamp(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; CallbackNative* callbackNative = NULL; uint32_t timestamp; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } timestamp = (*busAttachment)->GetTimestamp(); CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK, timestamp); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getPeerSecurityEnabled(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; CallbackNative* callbackNative = NULL; bool enabled; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } enabled = (*busAttachment)->IsPeerSecurityEnabled(); CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK, enabled); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::create(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String applicationName; bool allowRemoteMessages = false; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } allowRemoteMessages = ToBoolean(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a boolean"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = plugin->Origin(applicationName); if (ER_OK != status) { goto exit; } QCC_DbgTrace(("applicationName=%s,allowRemoteMessages=%d", applicationName.c_str(), allowRemoteMessages)); { qcc::String name = plugin->ToFilename(applicationName); const char* cname = name.c_str(); busAttachment = new BusAttachment(cname, allowRemoteMessages); } ATTRIBUTE("globalGUIDString", &_BusAttachmentHost::getGlobalGUIDString, 0); ATTRIBUTE("uniqueName", &_BusAttachmentHost::getUniqueName, 0); OPERATION("addLogonEntry", &_BusAttachmentHost::addLogonEntry); OPERATION("addMatch", &_BusAttachmentHost::addMatch); OPERATION("advertiseName", &_BusAttachmentHost::advertiseName); OPERATION("bindSessionPort", &_BusAttachmentHost::bindSessionPort); OPERATION("cancelAdvertiseName", &_BusAttachmentHost::cancelAdvertiseName); OPERATION("cancelFindAdvertisedName", &_BusAttachmentHost::cancelFindAdvertisedName); OPERATION("cancelFindAdvertisedNameByTransport", &_BusAttachmentHost::cancelFindAdvertisedNameByTransport); OPERATION("cancelWhoImplements", &_BusAttachmentHost::cancelWhoImplements); OPERATION("clearKeyStore", &_BusAttachmentHost::clearKeyStore); OPERATION("clearKeys", &_BusAttachmentHost::clearKeys); OPERATION("connect", &_BusAttachmentHost::connect); OPERATION("createInterface", &_BusAttachmentHost::createInterface); OPERATION("createInterfacesFromXML", &_BusAttachmentHost::createInterfacesFromXML); OPERATION("disconnect", &_BusAttachmentHost::disconnect); OPERATION("enablePeerSecurity", &_BusAttachmentHost::enablePeerSecurity); OPERATION("findAdvertisedName", &_BusAttachmentHost::findAdvertisedName); OPERATION("findAdvertisedNameByTransport", &_BusAttachmentHost::findAdvertisedNameByTransport); OPERATION("getAboutObj", &_BusAttachmentHost::getAboutObj); OPERATION("getInterface", &_BusAttachmentHost::getInterface); OPERATION("getInterfaces", &_BusAttachmentHost::getInterfaces); OPERATION("getKeyExpiration", &_BusAttachmentHost::getKeyExpiration); OPERATION("getPeerGUID", &_BusAttachmentHost::getPeerGUID); OPERATION("getPeerSecurityEnabled", &_BusAttachmentHost::getPeerSecurityEnabled); OPERATION("getProxyBusObject", &_BusAttachmentHost::getProxyBusObject); OPERATION("getTimestamp", &_BusAttachmentHost::getTimestamp); OPERATION("joinSession", &_BusAttachmentHost::joinSession); OPERATION("leaveSession", &_BusAttachmentHost::leaveSession); OPERATION("removeSessionMember", &_BusAttachmentHost::removeSessionMember); OPERATION("getSessionFd", &_BusAttachmentHost::getSessionFd); OPERATION("nameHasOwner", &_BusAttachmentHost::nameHasOwner); OPERATION("registerAboutListener", &_BusAttachmentHost::registerAboutListener); OPERATION("registerBusListener", &_BusAttachmentHost::registerBusListener); OPERATION("registerBusObject", &_BusAttachmentHost::registerBusObject); OPERATION("registerSignalHandler", &_BusAttachmentHost::registerSignalHandler); OPERATION("releaseName", &_BusAttachmentHost::releaseName); OPERATION("reloadKeyStore", &_BusAttachmentHost::reloadKeyStore); OPERATION("removeMatch", &_BusAttachmentHost::removeMatch); OPERATION("requestName", &_BusAttachmentHost::requestName); OPERATION("setDaemonDebug", &_BusAttachmentHost::setDaemonDebug); OPERATION("setKeyExpiration", &_BusAttachmentHost::setKeyExpiration); OPERATION("setLinkTimeout", &_BusAttachmentHost::setLinkTimeout); OPERATION("setSessionListener", &_BusAttachmentHost::setSessionListener); OPERATION("unbindSessionPort", &_BusAttachmentHost::unbindSessionPort); OPERATION("unregisterAboutListener", &_BusAttachmentHost::unregisterAboutListener); OPERATION("unregisterAllAboutListeners", &_BusAttachmentHost::unregisterAllAboutListeners); OPERATION("unregisterBusListener", &_BusAttachmentHost::unregisterBusListener); OPERATION("unregisterBusObject", &_BusAttachmentHost::unregisterBusObject); OPERATION("unregisterSignalHandler", &_BusAttachmentHost::unregisterSignalHandler); OPERATION("whoImplements", &_BusAttachmentHost::whoImplements); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::destroy(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("_BusAttachmentHost.%s(%d) %p", __FUNCTION__, argCount, this)); bool typeError = false; CallbackNative* callbackNative = NULL; REMOVE_ATTRIBUTE("globalGUIDString"); REMOVE_ATTRIBUTE("uniqueName"); REMOVE_OPERATION("addLogonEntry"); REMOVE_OPERATION("addMatch"); REMOVE_OPERATION("advertiseName"); REMOVE_OPERATION("bindSessionPort"); REMOVE_OPERATION("cancelAdvertiseName"); REMOVE_OPERATION("cancelFindAdvertisedName"); REMOVE_OPERATION("cancelFindAdvertisedNameByTransport"); REMOVE_OPERATION("cancelWhoImplements"); REMOVE_OPERATION("clearKeyStore"); REMOVE_OPERATION("clearKeys"); REMOVE_OPERATION("connect"); REMOVE_OPERATION("createInterface"); REMOVE_OPERATION("createInterfacesFromXML"); REMOVE_OPERATION("disconnect"); REMOVE_OPERATION("enablePeerSecurity"); REMOVE_OPERATION("findAdvertisedName"); REMOVE_OPERATION("findAdvertisedNameByTransport"); REMOVE_OPERATION("getAboutObj"); REMOVE_OPERATION("getInterface"); REMOVE_OPERATION("getInterfaces"); REMOVE_OPERATION("getKeyExpiration"); REMOVE_OPERATION("getPeerGUID"); REMOVE_OPERATION("getPeerSecurityEnabled"); REMOVE_OPERATION("getProxyBusObject"); REMOVE_OPERATION("getTimestamp"); REMOVE_OPERATION("joinSession"); REMOVE_OPERATION("leaveSession"); REMOVE_OPERATION("removeSessionMember"); REMOVE_OPERATION("getSessionFd"); REMOVE_OPERATION("nameHasOwner"); REMOVE_OPERATION("registerAboutListener"); REMOVE_OPERATION("registerBusListener"); REMOVE_OPERATION("registerBusObject"); REMOVE_OPERATION("registerSignalHandler"); REMOVE_OPERATION("releaseName"); REMOVE_OPERATION("reloadKeyStore"); REMOVE_OPERATION("removeMatch"); REMOVE_OPERATION("requestName"); REMOVE_OPERATION("setDaemonDebug"); REMOVE_OPERATION("setKeyExpiration"); REMOVE_OPERATION("setLinkTimeout"); REMOVE_OPERATION("setSessionListener"); REMOVE_OPERATION("unbindSessionPort"); REMOVE_OPERATION("unregisterAboutListener"); REMOVE_OPERATION("unregisterAllAboutListeners"); REMOVE_OPERATION("unregisterBusListener"); REMOVE_OPERATION("unregisterBusObject"); REMOVE_OPERATION("unregisterSignalHandler"); REMOVE_OPERATION("whoImplements"); if (argCount > 0) { callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } /* * destroy() is a no-op. Under NPAPI, the runtime takes care of * garbage collecting this object and under Cordova, the JavaScript * side of destroy() explicitly releases the reference (effectively * garbage-collecting this object). */ CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; } exit: delete callbackNative; VOID_TO_NPVARIANT(*result); stopAndJoin(); return !typeError; } bool _BusAttachmentHost::connect(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String connectSpec; CallbackNative* callbackNative = NULL; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } if (argCount > 1) { connectSpec = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } } else { #if defined(QCC_OS_GROUP_WINDOWS) connectSpec = "tcp:addr=127.0.0.1,port=9955"; #else connectSpec = "unix:abstract=alljoyn"; #endif } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("connectSpec=%s", connectSpec.c_str())); status = ER_OK; if (!(*busAttachment)->IsStarted()) { status = (*busAttachment)->Start(); } if ((ER_OK == status) && !(*busAttachment)->IsConnected()) { status = Connect(plugin, connectSpec.c_str()); } CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::createInterface(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String name; InterfaceDescriptionNative* interfaceDescriptionNative = NULL; CallbackNative* callbackNative = NULL; bool typeError = false; QStatus status = ER_OK; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } interfaceDescriptionNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !interfaceDescriptionNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = InterfaceDescriptionNative::CreateInterface(plugin, *busAttachment, interfaceDescriptionNative); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; delete interfaceDescriptionNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::createInterfacesFromXML(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String xml; CallbackNative* callbackNative = NULL; bool typeError = false; QStatus status = ER_OK; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } xml = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = (*busAttachment)->CreateInterfacesFromXml(xml.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::registerSignalHandler(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); MessageListenerNative* signalListener = NULL; qcc::String signalName; qcc::String sourcePath; CallbackNative* callbackNative = NULL; const ajn::InterfaceDescription::Member* signal; QStatus status = ER_OK; SignalReceiver* signalReceiver = NULL; bool typeError = false; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } signalListener = ToNativeObject(plugin, args[0], typeError); if (typeError || !signalListener) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } signalName = ToDOMString(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } if (argCount > 3) { sourcePath = ToDOMString(plugin, args[2], typeError); if (typeError) { plugin->RaiseTypeError("argument 2 is not a string"); goto exit; } } status = GetSignal(signalName, signal); if (ER_OK == status) { for (std::list::iterator it = signalReceivers.begin(); it != signalReceivers.end(); ++it) { if ((*((*it)->env->signalListener) == *signalListener) && (*((*it)->env->signal) == *signal) && ((*it)->env->sourcePath == sourcePath)) { /* Identical receiver registered, nothing to do. */ goto exit; } } signalReceiver = new SignalReceiver(plugin, *busAttachment, signalListener, signal, sourcePath); signalListener = NULL; /* signalReceiver now owns signalListener */ status = (*busAttachment)->RegisterSignalHandler( signalReceiver, static_cast(&SignalReceiver::SignalHandler), signal, sourcePath.empty() ? 0 : sourcePath.c_str()); if (ER_OK != status) { goto exit; } qcc::String rule = MatchRule(signal, sourcePath); status = (*busAttachment)->AddMatch(rule.c_str()); if (ER_OK == status) { signalReceivers.push_back(signalReceiver); signalReceiver = NULL; /* signalReceivers now owns signalReceiver */ } else { (*busAttachment)->UnregisterSignalHandler( signalReceiver, static_cast(&SignalReceiver::SignalHandler), signal, sourcePath.empty() ? 0 : sourcePath.c_str()); } } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; delete signalReceiver; delete signalListener; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::unregisterBusObject(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String name; CallbackNative* callbackNative = NULL; std::map::iterator it; QStatus status = ER_OK; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } it = busObjectListeners.find(name); if (it != busObjectListeners.end()) { BusObjectListener* busObjectListener = it->second; (*busAttachment)->UnregisterBusObject(*busObjectListener->env->busObject); busObjectListeners.erase(it); delete busObjectListener; } CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::disconnect(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } if ((*busAttachment)->IsStarted() && !(*busAttachment)->IsStopping() && (*busAttachment)->IsConnected()) { status = (*busAttachment)->Disconnect(); } if ((ER_OK == status) && (*busAttachment)->IsStarted()) { status = (*busAttachment)->Stop(); } CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::registerBusObject(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); /* * This function actually works with 3 forms of the registerBusObject JS method: * registerBusObject(objPath, busObject, callback) * registerBusObject(objPath, busObject, secure, callback) * registerBusObject(objPath, busObject, secure, announce, callback) * * Note that the 'secure' parameter is optional. It defaults to false. * The 'announce' parameter is optional, too. It defaults to false, which is UNANNOUNCE the interface. * If true then it indicates ANNOUNCE the interface. */ qcc::String name; BusObjectNative* busObjectNative = NULL; CallbackNative* callbackNative = NULL; BusObjectListener* busObjectListener = NULL; const NPVariant* arg = args; bool secure = false; QStatus status = ER_OK; bool announce = false; ajn::BusObject::AnnounceFlag isAnnounced = ajn::BusObject::UNANNOUNCED; bool typeError = false; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, *arg, typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } ++arg; busObjectNative = ToNativeObject(plugin, *arg, typeError); if (typeError || !busObjectNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } ++arg; /* * This method used to only take the object path, object reference, and * callback as its only parameters. It now takes a boolean to indicate if * the object should be secure. This new secure parameter should belong * between the object reference and callback parameters. We'll use the * argCount to determine if the secure parameter is specified or not. */ if (argCount > 3) { secure = ToBoolean(plugin, *arg, typeError); if (typeError) { plugin->RaiseTypeError("argument 2 is not a boolean"); goto exit; } ++arg; } /* * This method now takes a boolean to indicate if * the object description value should be announced. * This new announce parameter should belong * between the secure and callback parameters. We'll use the * argCount to determine if the announce parameter is specified or not. */ if (argCount > 4) { announce = ToBoolean(plugin, *arg, typeError); if (typeError) { plugin->RaiseTypeError("argument 3 is not a boolean"); goto exit; } ++arg; } callbackNative = ToNativeObject(plugin, *arg, typeError); if (typeError || !callbackNative) { typeError = true; if (argCount > 4) { plugin->RaiseTypeError("argument 4 is not an object"); } else { plugin->RaiseTypeError((argCount > 3) ? "argument 3 is not an object" : "argument 2 is not an object"); } goto exit; } if (announce) { isAnnounced = ajn::BusObject::ANNOUNCED; } busObjectListener = new BusObjectListener(plugin, *busAttachment, name.c_str(), busObjectNative); busObjectNative = NULL; /* busObject now owns busObjectNative */ status = busObjectListener->AddInterfaceAndMethodHandlers(isAnnounced); if (ER_OK != status) { goto exit; } status = (*busAttachment)->RegisterBusObject(*busObjectListener->env->busObject, secure); if (ER_OK == status) { std::pair element(name, busObjectListener); busObjectListeners.insert(element); busObjectListener = NULL; /* busObjectListeners now owns busObjectListener */ } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; delete busObjectListener; delete busObjectNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::unregisterSignalHandler(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); MessageListenerNative* signalListener = NULL; qcc::String signalName; qcc::String sourcePath; CallbackNative* callbackNative = NULL; const ajn::InterfaceDescription::Member* signal; QStatus status = ER_OK; bool typeError = false; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } signalListener = ToNativeObject(plugin, args[0], typeError); if (typeError || !signalListener) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } signalName = ToDOMString(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } if (argCount > 2) { sourcePath = ToDOMString(plugin, args[2], typeError); if (typeError) { plugin->RaiseTypeError("argument 2 is not a string"); goto exit; } } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 3 is not an object"); goto exit; } status = GetSignal(signalName, signal); if (ER_OK == status) { std::list::iterator it; for (it = signalReceivers.begin(); it != signalReceivers.end(); ++it) { if ((*((*it)->env->signalListener) == *signalListener) && (*((*it)->env->signal) == *signal) && ((*it)->env->sourcePath == sourcePath)) { break; } } if (it != signalReceivers.end()) { status = (*busAttachment)->UnregisterSignalHandler( (*it), static_cast(&SignalReceiver::SignalHandler), signal, sourcePath.empty() ? 0 : sourcePath.c_str()); if (ER_OK != status) { goto exit; } qcc::String rule = MatchRule(signal, sourcePath); status = (*busAttachment)->RemoveMatch(rule.c_str()); if (ER_OK == status) { SignalReceiver* signalReceiver = (*it); signalReceivers.erase(it); delete signalReceiver; } else { (*busAttachment)->RegisterSignalHandler( (*it), static_cast(&SignalReceiver::SignalHandler), signal, sourcePath.empty() ? 0 : sourcePath.c_str()); } } } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; delete signalListener; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::registerAboutListener(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); AboutListenerNative* aboutListenerNative = NULL; CallbackNative* callbackNative = NULL; AboutListener* aboutListener = NULL; std::list::iterator it; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } aboutListenerNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !aboutListenerNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } for (it = aboutListeners.begin(); it != aboutListeners.end(); ++it) { if (*((*it)->env->aboutListenerNative) == *aboutListenerNative) { /* Identical listener registered, nothing to do. */ goto exit; } } aboutListener = new AboutListener(plugin, this, *busAttachment, aboutListenerNative); aboutListenerNative = NULL; /* aboutListener now owns aboutListenerNative */ (*busAttachment)->RegisterAboutListener(*aboutListener); aboutListeners.push_back(aboutListener); aboutListener = NULL; /* aboutListeners now owns aboutListener */ exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; } delete aboutListener; delete callbackNative; delete aboutListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::registerBusListener(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); BusListenerNative* busListenerNative = NULL; CallbackNative* callbackNative = NULL; BusListener* busListener = NULL; std::list::iterator it; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } busListenerNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !busListenerNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } for (it = busListeners.begin(); it != busListeners.end(); ++it) { if (*((*it)->env->busListenerNative) == *busListenerNative) { /* Identical listener registered, nothing to do. */ goto exit; } } busListener = new BusListener(plugin, this, *busAttachment, busListenerNative); busListenerNative = NULL; /* busListener now owns busListenerNative */ (*busAttachment)->RegisterBusListener(*busListener); busListeners.push_back(busListener); busListener = NULL; /* busListeners now owns busListener */ exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; } delete busListener; delete callbackNative; delete busListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::unregisterAboutListener(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); AboutListenerNative* aboutListenerNative = NULL; CallbackNative* callbackNative = NULL; std::list::iterator it; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } aboutListenerNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !aboutListenerNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } for (it = aboutListeners.begin(); it != aboutListeners.end(); ++it) { if (*((*it)->env->aboutListenerNative) == *aboutListenerNative) { break; } } if (it != aboutListeners.end()) { AboutListener* aboutListener = (*it); (*busAttachment)->UnregisterAboutListener(*aboutListener); aboutListeners.erase(it); delete aboutListener; } CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; exit: delete callbackNative; delete aboutListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::unregisterAllAboutListeners(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; std::list::iterator it; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } (*busAttachment)->UnregisterAllAboutListeners(); for (it = aboutListeners.begin(); it != aboutListeners.end(); ++it) { delete *it; } aboutListeners.clear(); CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::unregisterBusListener(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); BusListenerNative* busListenerNative = NULL; CallbackNative* callbackNative = NULL; std::list::iterator it; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } busListenerNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !busListenerNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } for (it = busListeners.begin(); it != busListeners.end(); ++it) { if (*((*it)->env->busListenerNative) == *busListenerNative) { break; } } if (it != busListeners.end()) { BusListener* busListener = (*it); (*busAttachment)->UnregisterBusListener(*busListener); busListeners.erase(it); delete busListener; } CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; exit: delete callbackNative; delete busListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::requestName(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String requestedName; uint32_t flags = 0; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } requestedName = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } if (argCount > 2) { flags = ToUnsignedLong(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("requestedName=%s,flags=0x%x", requestedName.c_str(), flags)); status = (*busAttachment)->RequestName(requestedName.c_str(), flags); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::releaseName(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String name; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("name=%s", name.c_str())); status = (*busAttachment)->ReleaseName(name.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::addMatch(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String rule; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } rule = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("rule=%s", rule.c_str())); status = (*busAttachment)->AddMatch(rule.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::removeMatch(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String rule; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } rule = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("rule=%s", rule.c_str())); status = (*busAttachment)->RemoveMatch(rule.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::whoImplements(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; CallbackNative* callbackNative = NULL; NPObject* inObject; NPVariant npvLength; QStatus status = ER_OK; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } switch (args[0].type) { // string case NPVariantType_String: { uint32_t UTF8Length = NPVARIANT_TO_STRING(args[0]).UTF8Length; const NPUTF8* UTF8Characters = NPVARIANT_TO_STRING(args[0]).UTF8Characters; char* chars = reinterpret_cast(NPN_MemAlloc(UTF8Length + 1)); strncpy(chars, UTF8Characters, UTF8Length); chars[UTF8Length] = 0; status = (*busAttachment)->WhoImplements(chars); break; } // array case NPVariantType_Object: { inObject = NPVARIANT_TO_OBJECT(args[0]); if (NPN_GetProperty(plugin->npp, inObject, NPN_GetStringIdentifier("length"), &npvLength)) { char** interfaces = NULL; int numberInterfaces = 0; numberInterfaces = npvLength.value.intValue; if (numberInterfaces > 0) { interfaces = new char*[numberInterfaces]; for (int32_t i = 0; i < numberInterfaces; ++i) { interfaces[i] = NULL; NPVariant curValue; NPN_GetProperty(plugin->npp, inObject, NPN_GetIntIdentifier(i), &curValue); if (!NPVARIANT_IS_VOID(curValue)) { int32_t utf8length = NPVARIANT_TO_STRING(curValue).UTF8Length; interfaces[i] = new char[utf8length + 1]; strncpy(interfaces[i], NPVARIANT_TO_STRING(curValue).UTF8Characters, utf8length); interfaces[i][utf8length] = 0; } NPN_ReleaseVariantValue(&curValue); } status = (*busAttachment)->WhoImplements(const_cast(interfaces), numberInterfaces); for (int32_t i = 0; i < numberInterfaces; ++i) delete[] interfaces[i]; delete[] interfaces; } else { status = (*busAttachment)->WhoImplements(NULL, 0); } } else { status = (*busAttachment)->WhoImplements(NULL, 0); } break; } case NPVariantType_Null: { status = (*busAttachment)->WhoImplements(NULL, 0); break; } default: { status = (*busAttachment)->WhoImplements(NULL, 0); break; } } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; VOID_TO_NPVARIANT(npvLength); VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::cancelWhoImplements(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; CallbackNative* callbackNative = NULL; NPObject* inObject; NPVariant npvLength; QStatus status = ER_OK; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } switch (args[0].type) { // string case NPVariantType_String: { uint32_t UTF8Length = NPVARIANT_TO_STRING(args[0]).UTF8Length; const NPUTF8* UTF8Characters = NPVARIANT_TO_STRING(args[0]).UTF8Characters; char* chars = reinterpret_cast(NPN_MemAlloc(UTF8Length + 1)); strncpy(chars, UTF8Characters, UTF8Length); chars[UTF8Length] = 0; status = (*busAttachment)->CancelWhoImplements(chars); break; } // array case NPVariantType_Object: { inObject = NPVARIANT_TO_OBJECT(args[0]); if (NPN_GetProperty(plugin->npp, inObject, NPN_GetStringIdentifier("length"), &npvLength)) { char** interfaces = NULL; int numberInterfaces = 0; numberInterfaces = npvLength.value.intValue; if (numberInterfaces > 0) { interfaces = new char*[numberInterfaces]; for (int32_t i = 0; i < numberInterfaces; ++i) { interfaces[i] = NULL; NPVariant curValue; NPN_GetProperty(plugin->npp, inObject, NPN_GetIntIdentifier(i), &curValue); if (!NPVARIANT_IS_VOID(curValue)) { int32_t utf8length = NPVARIANT_TO_STRING(curValue).UTF8Length; interfaces[i] = new char[utf8length + 1]; strncpy(interfaces[i], NPVARIANT_TO_STRING(curValue).UTF8Characters, utf8length); interfaces[i][utf8length] = 0; } NPN_ReleaseVariantValue(&curValue); } status = (*busAttachment)->CancelWhoImplements(const_cast(interfaces), numberInterfaces); for (int32_t i = 0; i < numberInterfaces; ++i) delete[] interfaces[i]; delete[] interfaces; } else { status = (*busAttachment)->CancelWhoImplements(NULL, 0); } } else { status = (*busAttachment)->CancelWhoImplements(NULL, 0); } break; } case NPVariantType_Null: { status = (*busAttachment)->CancelWhoImplements(NULL, 0); break; } default: { status = (*busAttachment)->CancelWhoImplements(NULL, 0); break; } } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; VOID_TO_NPVARIANT(npvLength); VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::advertiseName(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String name; uint16_t transports; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } transports = ToUnsignedShort(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("name=%s,transports=0x%x", name.c_str(), transports)); status = (*busAttachment)->AdvertiseName(name.c_str(), transports); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::cancelAdvertiseName(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String name; uint16_t transports; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } transports = ToUnsignedShort(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("name=%s,transports=0x%x", name.c_str(), transports)); status = (*busAttachment)->CancelAdvertiseName(name.c_str(), transports); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::findAdvertisedName(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String namePrefix; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } namePrefix = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("namePrefix=%s", namePrefix.c_str())); status = (*busAttachment)->FindAdvertisedName(namePrefix.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::findAdvertisedNameByTransport(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String namePrefix; uint16_t transports; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } namePrefix = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } transports = ToUnsignedShort(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("namePrefix=%s,transports=0x%x", namePrefix.c_str(), transports)); status = (*busAttachment)->FindAdvertisedNameByTransport(namePrefix.c_str(), transports); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::cancelFindAdvertisedName(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String namePrefix; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } namePrefix = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("namePrefix=%s", namePrefix.c_str())); status = (*busAttachment)->CancelFindAdvertisedName(namePrefix.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::cancelFindAdvertisedNameByTransport(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String namePrefix; uint16_t transports; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } namePrefix = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } transports = ToUnsignedShort(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("namePrefix=%s,transports=0x%x", namePrefix.c_str(), transports)); status = (*busAttachment)->CancelFindAdvertisedNameByTransport(namePrefix.c_str(), transports); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::bindSessionPort(const NPVariant* args, uint32_t argCount, NPVariant* npresult) { QCC_DbgTrace(("%s", __FUNCTION__)); ajn::SessionPort sessionPort = ajn::SESSION_PORT_ANY; ajn::SessionOpts sessionOpts; AcceptSessionJoinerListenerNative* acceptSessionListenerNative = NULL; SessionJoinedListenerNative* sessionJoinedListenerNative = NULL; SessionLostListenerNative* sessionLostListenerNative = NULL; SessionMemberAddedListenerNative* sessionMemberAddedListenerNative = NULL; SessionMemberRemovedListenerNative* sessionMemberRemovedListenerNative = NULL; SessionListener::Env sessionListenerEnv(plugin, *busAttachment); CallbackNative* callbackNative = NULL; SessionPortListener* sessionPortListener = NULL; QStatus status = ER_OK; NPVariant result; /* * Pull out the parameters from the native object. */ bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } if (!NPVARIANT_IS_OBJECT(args[0])) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("port"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionPort = ToUnsignedShort(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'port' is not a number"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("traffic"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionOpts.traffic = (ajn::SessionOpts::TrafficType) ToOctet(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'traffic' is not a number"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("isMultipoint"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionOpts.isMultipoint = ToBoolean(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'isMultipoint' is not a boolean"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("proximity"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionOpts.proximity = ToOctet(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'proximity' is not a number"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("transports"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionOpts.transports = ToUnsignedShort(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'transports' is not a number"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onAccept"), &result); if (!NPVARIANT_IS_VOID(result)) { acceptSessionListenerNative = ToNativeObject(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'onAccept' is not an object"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onJoined"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionJoinedListenerNative = ToNativeObject(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'onJoined' is not an object"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onLost"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionLostListenerNative = ToNativeObject(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'onLost' is not an object"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onMemberAdded"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionMemberAddedListenerNative = ToNativeObject(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'onMemberAdded' is not an object"); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onMemberRemoved"), &result); if (!NPVARIANT_IS_VOID(result)) { sessionMemberRemovedListenerNative = ToNativeObject(plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { plugin->RaiseTypeError("'onMemberRemoved' is not an object"); goto exit; } QCC_DbgTrace(("sessionPort=%u", sessionPort)); if (sessionLostListenerNative || sessionMemberAddedListenerNative || sessionMemberRemovedListenerNative) { sessionListenerEnv = SessionListener::Env(plugin, *busAttachment, sessionLostListenerNative, sessionMemberAddedListenerNative, sessionMemberRemovedListenerNative); /* sessionListener now owns session*ListenerNative */ sessionLostListenerNative = NULL; sessionMemberAddedListenerNative = NULL; sessionMemberRemovedListenerNative = NULL; } sessionPortListener = new SessionPortListener(plugin, this, *busAttachment, acceptSessionListenerNative, sessionJoinedListenerNative, sessionListenerEnv); acceptSessionListenerNative = NULL; /* sessionPortListener now owns acceptSessionListenerNative */ sessionJoinedListenerNative = NULL; /* sessionPortListener now owns sessionJoinedListenerNative */ status = (*busAttachment)->BindSessionPort(sessionPort, sessionOpts, *sessionPortListener); if (ER_OK == status) { std::pair element(sessionPort, sessionPortListener); sessionPortListeners.insert(element); sessionPortListener = NULL; /* sessionPortListeners now owns sessionPort */ } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status, sessionPort); callbackNative = NULL; } delete callbackNative; delete acceptSessionListenerNative; delete sessionJoinedListenerNative; delete sessionLostListenerNative; delete sessionMemberAddedListenerNative; delete sessionMemberRemovedListenerNative; delete sessionPortListener; VOID_TO_NPVARIANT(*npresult); return !typeError; } bool _BusAttachmentHost::unbindSessionPort(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; ajn::SessionPort sessionPort; CallbackNative* callbackNative = NULL; std::map::iterator it; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } sessionPort = ToUnsignedShort(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("sessionPort=%u", sessionPort)); it = sessionPortListeners.find(sessionPort); if (it != sessionPortListeners.end()) { SessionPortListener* listener = it->second; QStatus status = listener->cancelEvent.SetEvent(); assert(ER_OK == status); if (ER_OK != status) { QCC_LogError(status, ("SetEvent failed")); /* Small chance of deadlock if this occurs. */ } } status = (*busAttachment)->UnbindSessionPort(sessionPort); if (ER_OK == status) { if (it != sessionPortListeners.end()) { SessionPortListener* listener = it->second; sessionPortListeners.erase(it); delete listener; } } CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::setSessionListener(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); ajn::SessionId id; SessionLostListenerNative* sessionLostListenerNative = NULL; SessionMemberAddedListenerNative* sessionMemberAddedListenerNative = NULL; SessionMemberRemovedListenerNative* sessionMemberRemovedListenerNative = NULL; CallbackNative* callbackNative = NULL; SessionListener* sessionListener = NULL; QStatus status = ER_OK; NPVariant variant; bool typeError = false; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } id = ToUnsignedLong(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a number"); goto exit; } if (NPVARIANT_IS_OBJECT(args[1])) { VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier("onLost"), &variant); sessionLostListenerNative = ToNativeObject(plugin, variant, typeError); NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'onLost' is not an object"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier("onMemberAdded"), &variant); sessionMemberAddedListenerNative = ToNativeObject(plugin, variant, typeError); NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'onMemberAdded' is not an object"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier("onMemberRemoved"), &variant); sessionMemberRemovedListenerNative = ToNativeObject(plugin, variant, typeError); NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'onMemberRemoved' is not an object"); goto exit; } } else if (!NPVARIANT_IS_NULL(args[1])) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object or null"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("id=%u", id)); if (sessionLostListenerNative || sessionMemberAddedListenerNative || sessionMemberRemovedListenerNative) { sessionListener = new SessionListener(plugin, *busAttachment, sessionLostListenerNative, sessionMemberAddedListenerNative, sessionMemberRemovedListenerNative); /* sessionListener now owns session*ListenerNative */ sessionLostListenerNative = NULL; sessionMemberAddedListenerNative = NULL; sessionMemberRemovedListenerNative = NULL; } status = (*busAttachment)->SetSessionListener(id, sessionListener); if (ER_OK == status) { /* Overwrite existing listener. */ std::map::iterator it = sessionListeners.find(id); if (it != sessionListeners.end()) { SessionListener* listener = it->second; sessionListeners.erase(it); delete listener; } if (sessionListener) { std::pair element(id, sessionListener); sessionListeners.insert(element); sessionListener = NULL; /* sessionListeners now owns sessionListener */ } } CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; delete sessionListener; delete sessionLostListenerNative; delete sessionMemberAddedListenerNative; delete sessionMemberRemovedListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::joinSession(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); BusAttachmentHost busAttachmentHost = BusAttachmentHost::wrap(this); qcc::String sessionHost; ajn::SessionPort sessionPort = ajn::SESSION_PORT_ANY; ajn::SessionOpts sessionOpts; SessionLostListenerNative* sessionLostListenerNative = NULL; SessionMemberAddedListenerNative* sessionMemberAddedListenerNative = NULL; SessionMemberRemovedListenerNative* sessionMemberRemovedListenerNative = NULL; CallbackNative* callbackNative = NULL; SessionListener* sessionListener = NULL; QStatus status = ER_OK; JoinSessionAsyncCB* callback = NULL; /* * Pull out the parameters from the native object. */ NPVariant variant; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } /* * Mandatory parameters */ if (!NPVARIANT_IS_OBJECT(args[0])) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("host"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionHost = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || sessionHost.empty()) { typeError = true; plugin->RaiseTypeError("property 'host' of argument 2 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("port"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionPort = ToUnsignedShort(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || (ajn::SESSION_PORT_ANY == sessionPort)) { typeError = true; plugin->RaiseTypeError("property 'port' of argument 2 is undefined or invalid"); goto exit; } /* * Optional parameters */ VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("traffic"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionOpts.traffic = (ajn::SessionOpts::TrafficType) ToOctet(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'traffic' is not a number"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("isMultipoint"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionOpts.isMultipoint = ToBoolean(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'isMultipoint' is not a boolean"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("proximity"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionOpts.proximity = ToOctet(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'proximity' is not a number"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("transports"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionOpts.transports = ToUnsignedShort(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'transports' is not a number"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onLost"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionLostListenerNative = ToNativeObject(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'onLost' is not an object"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onMemberAdded"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionMemberAddedListenerNative = ToNativeObject(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'onMemberAdded' is not an object"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("onMemberRemoved"), &variant); if (!NPVARIANT_IS_VOID(variant)) { sessionMemberRemovedListenerNative = ToNativeObject(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'onMemberRemoved' is not an object"); goto exit; } QCC_DbgTrace(("sessionHost=%s,sessionPort=%u,sessionOpts={traffic=%x,isMultipoint=%d,proximity=%x,transports=%x}", sessionHost.c_str(), sessionPort, sessionOpts.traffic, sessionOpts.isMultipoint, sessionOpts.proximity, sessionOpts.transports)); sessionListener = new SessionListener(plugin, *busAttachment, sessionLostListenerNative, sessionMemberAddedListenerNative, sessionMemberRemovedListenerNative); /* sessionListener now owns session*ListenerNative */ sessionLostListenerNative = NULL; sessionMemberAddedListenerNative = NULL; sessionMemberRemovedListenerNative = NULL; callback = new JoinSessionAsyncCB(plugin, busAttachmentHost, *busAttachment, callbackNative, sessionListener); callbackNative = NULL; /* callback now owns callbackNative */ sessionListener = NULL; /* callback now owns sessionListener */ status = (*busAttachment)->JoinSessionAsync(sessionHost.c_str(), sessionPort, callback->env->sessionListener, sessionOpts, callback); if (ER_OK == status) { callback = NULL; /* alljoyn owns callback */ } else { callback->env->status = status; } exit: delete callbackNative; delete callback; delete sessionListener; delete sessionLostListenerNative; delete sessionMemberAddedListenerNative; delete sessionMemberRemovedListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::leaveSession(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; ajn::SessionId id; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } id = ToUnsignedLong(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("id=%u", id)); status = (*busAttachment)->LeaveSession(id); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::removeSessionMember(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String name; ajn::SessionId id; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } id = ToUnsignedLong(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a number"); goto exit; } name = ToDOMString(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("id = %u name=%s", id, name.c_str())); status = (*busAttachment)->RemoveSessionMember(id, name.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getSessionFd(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; ajn::SessionId id; CallbackNative* callbackNative = NULL; qcc::SocketFd sockFd; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } id = ToUnsignedLong(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("id=%u", id)); status = (*busAttachment)->GetSessionFd(id, sockFd); if (ER_OK == status) { SocketFdHost socketFdHost(plugin, sockFd); CallbackNative::DispatchCallback(plugin, callbackNative, status, socketFdHost); } else { CallbackNative::DispatchCallback(plugin, callbackNative, status); } callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::setLinkTimeout(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; ajn::SessionId id; uint32_t linkTimeout; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } id = ToUnsignedLong(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } linkTimeout = ToUnsignedLong(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 2 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("id=%u,linkTimeout=%u", id, linkTimeout)); status = (*busAttachment)->SetLinkTimeout(id, linkTimeout); CallbackNative::DispatchCallback(plugin, callbackNative, status, linkTimeout); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::nameHasOwner(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String name; CallbackNative* callbackNative = NULL; bool has; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("name=%s", name.c_str())); status = (*busAttachment)->NameHasOwner(name.c_str(), has); CallbackNative::DispatchCallback(plugin, callbackNative, status, has); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::setDaemonDebug(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String module; uint32_t level; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } module = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } level = ToUnsignedLong(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a number"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("module=%s,level=%u", module.c_str(), level)); status = (*busAttachment)->SetDaemonDebug(module.c_str(), level); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::enablePeerSecurity(const NPVariant* args, uint32_t argCount, NPVariant* result) { qcc::String authMechanisms; AuthListenerNative* authListenerNative = NULL; CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; const char* keyStoreFileName = NULL; qcc::String fileName; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } authMechanisms = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } if (argCount > 2) { authListenerNative = ToNativeObject(plugin, args[1], typeError); if (typeError) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } if (authListener) { status = ER_BUS_ALREADY_LISTENING; goto exit; } status = (*busAttachment)->Start(); if ((ER_OK != status) && (ER_BUS_BUS_ALREADY_STARTED != status)) { goto exit; } authListener = new AuthListener(plugin, *busAttachment, authMechanisms, authListenerNative); authListenerNative = NULL; /* authListener now owns authListenerNative */ fileName = plugin->KeyStoreFileName(); if (!fileName.empty()) { keyStoreFileName = fileName.c_str(); } status = (*busAttachment)->EnablePeerSecurity(authListener->env->authMechanisms.c_str(), authListener, keyStoreFileName, true); if (ER_OK != status) { delete authListener; authListener = NULL; } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; delete authListenerNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::reloadKeyStore(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } status = (*busAttachment)->ReloadKeyStore(); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::clearKeyStore(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } (*busAttachment)->ClearKeyStore(); CallbackNative::DispatchCallback(plugin, callbackNative, ER_OK); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::clearKeys(const NPVariant* args, uint32_t argCount, NPVariant* result) { QStatus status = ER_OK; bool typeError = false; qcc::String guid; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } guid = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = (*busAttachment)->ClearKeys(guid); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getInterface(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String name; CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; InterfaceDescriptionNative* interfaceDescriptionNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } interfaceDescriptionNative = InterfaceDescriptionNative::GetInterface(plugin, *busAttachment, name); CallbackNative::DispatchCallback(plugin, callbackNative, status, interfaceDescriptionNative); interfaceDescriptionNative = NULL; callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getInterfaces(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; size_t numIfaces; const ajn::InterfaceDescription** ifaces = NULL; InterfaceDescriptionNative** descs = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } numIfaces = (*busAttachment)->GetInterfaces(); ifaces = new const ajn::InterfaceDescription*[numIfaces]; (*busAttachment)->GetInterfaces(ifaces, numIfaces); descs = new InterfaceDescriptionNative*[numIfaces]; for (uint32_t i = 0; i < numIfaces; ++i) { descs[i] = InterfaceDescriptionNative::GetInterface(plugin, *busAttachment, ifaces[i]->GetName()); } CallbackNative::DispatchCallback(plugin, callbackNative, status, descs, numIfaces); descs = NULL; callbackNative = NULL; exit: delete callbackNative; delete[] descs; delete[] ifaces; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getKeyExpiration(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String guid; CallbackNative* callbackNative = NULL; uint32_t timeout; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } guid = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("guid=%s", guid.c_str())); status = (*busAttachment)->GetKeyExpiration(guid, timeout); CallbackNative::DispatchCallback(plugin, callbackNative, status, timeout); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::setKeyExpiration(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String guid; uint32_t timeout; CallbackNative* callbackNative = NULL; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } guid = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } timeout = ToUnsignedLong(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } QCC_DbgTrace(("guid=%s,timeout=%u", guid.c_str(), timeout)); status = (*busAttachment)->SetKeyExpiration(guid, timeout); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::addLogonEntry(const NPVariant* args, uint32_t argCount, NPVariant* result) { bool typeError = false; QStatus status = ER_OK; qcc::String authMechanism; qcc::String userName; qcc::String password; CallbackNative* callbackNative = NULL; if (argCount < 4) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } authMechanism = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } userName = ToDOMString(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } password = ToDOMString(plugin, args[2], typeError); if (typeError) { plugin->RaiseTypeError("argument 2 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[3], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 3 is not an object"); goto exit; } status = (*busAttachment)->AddLogonEntry(authMechanism.c_str(), userName.c_str(), NPVARIANT_IS_NULL(args[2]) ? 0 : password.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getPeerGUID(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String name; CallbackNative* callbackNative = NULL; qcc::String guid; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = (*busAttachment)->GetPeerGUID(name.c_str(), guid); CallbackNative::DispatchCallback(plugin, callbackNative, status, guid); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } QStatus _BusAttachmentHost::GetSignal(const qcc::String& name, const ajn::InterfaceDescription::Member*& signal) { size_t dot = name.find_last_of('.'); if (qcc::String::npos == dot) { QCC_LogError(ER_BUS_BAD_MEMBER_NAME, ("Can't find '.' in '%s'", name.c_str())); return ER_BUS_BAD_MEMBER_NAME; } qcc::String interfaceName = name.substr(0, dot); qcc::String signalName = name.substr(dot + 1); QCC_DbgTrace(("interfaceName=%s,signalName=%s", interfaceName.c_str(), signalName.c_str())); const ajn::InterfaceDescription* interface = (*busAttachment)->GetInterface(interfaceName.c_str()); if (!interface) { QCC_LogError(ER_BUS_UNKNOWN_INTERFACE, ("Don't know about interface '%s'", interfaceName.c_str())); return ER_BUS_UNKNOWN_INTERFACE; } signal = interface->GetMember(signalName.c_str()); if (!signal) { QCC_LogError(ER_BUS_INTERFACE_NO_SUCH_MEMBER, ("Don't know about signal '%s' in interface '%s'", signalName.c_str(), interfaceName.c_str())); return ER_BUS_INTERFACE_NO_SUCH_MEMBER; } return ER_OK; } qcc::String _BusAttachmentHost::MatchRule(const ajn::InterfaceDescription::Member* signal, const qcc::String& sourcePath) { qcc::String rule = "type='signal',member='" + signal->name + "',interface='" + signal->iface->GetName() + "'"; if (!sourcePath.empty()) { rule += ",path='" + sourcePath + "'"; } return rule; } bool _BusAttachmentHost::getAboutObj(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } delete aboutObj; aboutObj = 0; aboutObj = new AboutObjHost(plugin, *busAttachment); CallbackNative::DispatchCallback(plugin, callbackNative, status, *aboutObj); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _BusAttachmentHost::getProxyBusObject(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); /* * This function actually works with 2 forms of the getProxyBusObject JS method: * getProxyBusObject(objPath, callback) * getProxyBusObject(objPath, secure, callback) * * Note that the 'secure' parameter is optional. It defaults to false. */ qcc::String name; qcc::String keyname; CallbackNative* callbackNative = NULL; std::map::iterator it; const NPVariant* arg = args; bool secure = false; QStatus status = ER_OK; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, *arg, typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } ++arg; /* * This method used to only take the object path, and callback as its only * parameters. It now takes a boolean to indicate if the proxy object * should be secure. This new secure parameter should belong between the * object path and callback parameters. We'll use the argCount to * determine if the secure parameter is specified or not. */ if (argCount > 2) { secure = ToBoolean(plugin, *arg, typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a boolean"); goto exit; } ++arg; } /* * Tweak the object path to include a distinction between a secure object * and an insecure object and save that as a key name used for looking up * existing ProxyBusObjectHost instances. This will handle the case of a * poorly written JS app that calls getProxyBusObject with secure=false * then later calls getProxyBusObject with secure=true. The JS app will * work the exact same way as a C++ app that instantiates ProxyBusObject * in the same manner. */ keyname = name + (secure ? "s" : "n"); callbackNative = ToNativeObject(plugin, *arg, typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError((argCount > 2) ? "argument 2 is not an object" : "argument 1 is not an object"); goto exit; } QCC_DbgTrace(("name=%s", name.c_str())); if (proxyBusObjects.find(keyname) == proxyBusObjects.end()) { qcc::String serviceName, path; std::map argMap; ParseName(name, serviceName, path, argMap); const char* cserviceName = serviceName.c_str(); const char* cpath = path.c_str(); ajn::SessionId sessionId = strtoul(argMap["sessionId"].c_str(), 0, 0); std::pair element(keyname, ProxyBusObjectHost(plugin, *busAttachment, cserviceName, cpath, sessionId)); proxyBusObjects.insert(element); } it = proxyBusObjects.find(keyname); CallbackNative::DispatchCallback(plugin, callbackNative, status, it->second); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } void _BusAttachmentHost::ParseName(const qcc::String& name, qcc::String& serviceName, qcc::String& path, std::map& argMap) { size_t slash = name.find_first_of('/'); size_t colon = name.find_last_of(':'); serviceName = name.substr(0, slash); path = name.substr(slash, colon - slash); qcc::String args = name.substr(colon); ajn::Transport::ParseArguments("", args.c_str(), argMap); /* Ignore any errors since args are optional */ } void _BusAttachmentHost::stopAndJoin() { QCC_DbgTrace(("%s %p", __FUNCTION__, this)); if (!busAttachment) { return; } /* * Ensure that all callbacks are complete before we start deleting things. */ (*busAttachment)->Stop(); for (std::map::iterator it = sessionPortListeners.begin(); it != sessionPortListeners.end(); ++it) { SessionPortListener* sessionPortListener = it->second; QStatus status = sessionPortListener->cancelEvent.SetEvent(); assert(ER_OK == status); if (ER_OK != status) { QCC_LogError(status, ("SetEvent failed")); /* Small chance of deadlock if this occurs. */ } } if (authListener) { QStatus status = authListener->cancelEvent.SetEvent(); assert(ER_OK == status); if (ER_OK != status) { QCC_LogError(status, ("SetEvent failed")); /* Small chance of deadlock if this occurs. */ } } (*busAttachment)->Join(); for (std::map::iterator it = busObjectListeners.begin(); it != busObjectListeners.end(); ++it) { BusObjectListener* busObjectListener = it->second; (*busAttachment)->UnregisterBusObject(*busObjectListener->env->busObject); delete busObjectListener; } for (std::map::iterator it = sessionListeners.begin(); it != sessionListeners.end(); ++it) { SessionListener* sessionListener = it->second; (*busAttachment)->SetSessionListener(it->first, 0); delete sessionListener; } for (std::map::iterator it = sessionPortListeners.begin(); it != sessionPortListeners.end(); ++it) { SessionPortListener* sessionPortListener = it->second; (*busAttachment)->UnbindSessionPort(it->first); delete sessionPortListener; } for (std::list::iterator it = busListeners.begin(); it != busListeners.end(); ++it) { BusListener* busListener = (*it); (*busAttachment)->UnregisterBusListener(*busListener); delete busListener; } for (std::list::iterator it = aboutListeners.begin(); it != aboutListeners.end(); ++it) { AboutListener* aboutListener = (*it); (*busAttachment)->UnregisterAboutListener(*aboutListener); delete aboutListener; } for (std::list::iterator it = signalReceivers.begin(); it != signalReceivers.end(); ++it) { SignalReceiver* signalReceiver = (*it); qcc::String rule = MatchRule(signalReceiver->env->signal, signalReceiver->env->sourcePath); (*busAttachment)->RemoveMatch(rule.c_str()); (*busAttachment)->UnregisterSignalHandler( signalReceiver, static_cast(&SignalReceiver::SignalHandler), signalReceiver->env->signal, signalReceiver->env->sourcePath.empty() ? 0 : signalReceiver->env->sourcePath.c_str()); delete signalReceiver; } if (authListener) { (*busAttachment)->EnablePeerSecurity(0, 0, 0, true); delete authListener; } if (aboutObj) { delete aboutObj; } aboutObj = NULL; proxyBusObjects.clear(); delete busAttachment; busAttachment = NULL; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SuccessListenerNative.cc0000644000175000017500000000257212620747066023405 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SuccessListenerNative.h" #include #define QCC_MODULE "ALLJOYN_JS" SuccessListenerNative::SuccessListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } SuccessListenerNative::~SuccessListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void SuccessListenerNative::onSuccess() { QCC_DbgTrace(("%s", __FUNCTION__)); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, 0, 0, &result); NPN_ReleaseVariantValue(&result); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageListenerNative.h0000644000175000017500000000235112620747066023216 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _MESSAGELISTENERNATIVE_H #define _MESSAGELISTENERNATIVE_H #include "MessageHost.h" #include "NativeObject.h" #include class MessageListenerNative : public NativeObject { public: MessageListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~MessageListenerNative(); void onMessage(MessageHost& message, const ajn::MsgArg* args, size_t numArgs); }; #endif // _MESSAGELISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HttpRequestHost.h0000644000175000017500000000376712620747066022117 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _HTTPREQUESTHOST_H #define _HTTPREQUESTHOST_H #include "HttpServer.h" #include "ScriptableObject.h" #include #include class _HttpRequestHost : public ScriptableObject { public: _HttpRequestHost(Plugin& plugin, HttpServer& httpServer, Http::Headers& requestHeaders, qcc::SocketStream& stream, qcc::SocketFd sessionFd); virtual ~_HttpRequestHost(); private: HttpServer httpServer; Http::Headers requestHeaders; qcc::SocketStream stream; qcc::SocketFd sessionFd; uint16_t status; qcc::String statusText; Http::Headers responseHeaders; bool getStatus(NPVariant* result); bool setStatus(const NPVariant* value); bool getStatusText(NPVariant* result); bool setStatusText(const NPVariant* value); bool getAllRequestHeaders(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getRequestHeader(const NPVariant* args, uint32_t argCount, NPVariant* result); bool setResponseHeader(const NPVariant* args, uint32_t argCount, NPVariant* result); bool send(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_HttpRequestHost> HttpRequestHost; #endif // _HTTPREQUESTHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/0000755000175000017500000000000012620747066017712 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/npn.cc0000644000175000017500000001433312620747066021020 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "npn.h" #include "PluginData.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" NPNetscapeFuncs* npn; #if defined(QCC_OS_GROUP_WINDOWS) HINSTANCE gHinstance; #endif void NPN_RetainVariantValue(const NPVariant*variant, NPVariant* retained) { switch (variant->type) { case NPVariantType_String: { uint32_t UTF8Length = NPVARIANT_TO_STRING(*variant).UTF8Length; const NPUTF8* UTF8Characters = NPVARIANT_TO_STRING(*variant).UTF8Characters; char* chars = reinterpret_cast(NPN_MemAlloc(UTF8Length + 1)); strncpy(chars, UTF8Characters, UTF8Length); chars[UTF8Length] = 0; STRINGN_TO_NPVARIANT(chars, UTF8Length, *retained); break; } case NPVariantType_Object: { *retained = *variant; NPN_RetainObject(NPVARIANT_TO_OBJECT(*retained)); break; } default: *retained = *variant; break; } } void NPN_PluginThreadAsyncCall(NPP npp, void (*func)(void*), void* userData) { QCC_DbgTrace(("%s", __FUNCTION__)); npn->pluginthreadasynccall(npp, func, userData); } /* * The other NPN_ functions are defined here to provide an entrypoint for debugging during * development. */ qcc::Thread* gPluginThread = NULL; #define ASSERT_MAIN_THREAD() \ do { \ assert(gPluginThread == qcc::Thread::GetThread()); \ if (gPluginThread != qcc::Thread::GetThread()) { \ QCC_LogError(ER_FAIL, ("NPN function called from external thread!")); \ } \ } while (0) #define ASSERT_NPP() \ do { \ assert(npp); \ if (!npp) { \ QCC_LogError(ER_FAIL, ("Null npp!")); \ } \ } while (0) NPObject* NPN_CreateObject(NPP npp, NPClass* aClass) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->createobject(npp, aClass); } bool NPN_Enumerate(NPP npp, NPObject* obj, NPIdentifier** identifier, uint32_t* count) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->enumerate(npp, obj, identifier, count); } bool NPN_Evaluate(NPP npp, NPObject* obj, NPString* script, NPVariant* result) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->evaluate(npp, obj, script, result); } NPIdentifier NPN_GetIntIdentifier(int32_t intid) { ASSERT_MAIN_THREAD(); return npn->getintidentifier(intid); } bool NPN_GetProperty(NPP npp, NPObject* obj, NPIdentifier propertyName, NPVariant* result) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->getproperty(npp, obj, propertyName, result); } NPIdentifier NPN_GetStringIdentifier(const NPUTF8* name) { ASSERT_MAIN_THREAD(); return npn->getstringidentifier(name); } NPError NPN_GetValue(NPP npp, NPNVariable variable, void* ret_value) { ASSERT_MAIN_THREAD(); return npn->getvalue(npp, variable, ret_value); } bool NPN_HasMethod(NPP npp, NPObject* obj, NPIdentifier propertyName) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->hasmethod(npp, obj, propertyName); } bool NPN_IdentifierIsString(NPIdentifier identifier) { ASSERT_MAIN_THREAD(); return npn->identifierisstring(identifier); } int32_t NPN_IntFromIdentifier(NPIdentifier identifier) { ASSERT_MAIN_THREAD(); return npn->intfromidentifier(identifier); } bool NPN_Invoke(NPP npp, NPObject* obj, NPIdentifier methodName, const NPVariant* args, uint32_t argCount, NPVariant* result) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->invoke(npp, obj, methodName, args, argCount, result); } bool NPN_InvokeDefault(NPP npp, NPObject* obj, const NPVariant* args, uint32_t argCount, NPVariant* result) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->invokeDefault(npp, obj, args, argCount, result); } void* NPN_MemAlloc(uint32_t size) { ASSERT_MAIN_THREAD(); return npn->memalloc(size); } void NPN_MemFree(void* ptr) { ASSERT_MAIN_THREAD(); return npn->memfree(ptr); } void NPN_ReleaseObject(NPObject* obj) { ASSERT_MAIN_THREAD(); return npn->releaseobject(obj); } void NPN_ReleaseVariantValue(NPVariant* variant) { ASSERT_MAIN_THREAD(); return npn->releasevariantvalue(variant); } NPObject* NPN_RetainObject(NPObject* obj) { ASSERT_MAIN_THREAD(); return npn->retainobject(obj); } void NPN_SetException(NPObject* obj, const NPUTF8* message) { ASSERT_MAIN_THREAD(); return npn->setexception(obj, message); } bool NPN_SetProperty(NPP npp, NPObject* obj, NPIdentifier propertyName, const NPVariant* value) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->setproperty(npp, obj, propertyName, value); } NPUTF8* NPN_UTF8FromIdentifier(NPIdentifier identifier) { ASSERT_MAIN_THREAD(); return npn->utf8fromidentifier(identifier); } NPError NPN_GetURLNotify(NPP npp, const char* url, const char* target, void* notifyData) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->geturlnotify(npp, url, target, notifyData); } const char* NPN_UserAgent(NPP npp) { ASSERT_MAIN_THREAD(); ASSERT_NPP(); return npn->uagent(npp); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/npn.h0000644000175000017500000000324412620747066020661 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _NPN_H #define _NPN_H #include #if defined(QCC_OS_LINUX) #include #endif #include #include #include #undef STRINGZ_TO_NPVARIANT #define STRINGZ_TO_NPVARIANT(_val, _v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_String; \ NPString str = { _val, (uint32_t)strlen(_val) }; \ (_v).value.stringValue = str; \ NP_END_MACRO #ifndef NPVARIANT_VOID #define NPVARIANT_VOID { NPVariantType_Void, { 0 } } #endif extern qcc::Thread* gPluginThread; #if defined(QCC_OS_GROUP_WINDOWS) extern HINSTANCE gHinstance; #endif void NPN_RetainVariantValue(const NPVariant*variant, NPVariant* retained); void NPN_PluginThreadAsyncCall(NPP instance, void (*func)(void*), void* userData); #endif // _NPN_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/npp.cc0000644000175000017500000002612412620747066021023 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "npn.h" #include "NativeObject.h" #include "PluginData.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" #define MAXREADY (64 * 1024) #define DATA_DELIVERY_DELAY_MS 10 /* Android-only */ NPError NPP_New(NPMIMEType pluginType, NPP npp, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved) { QCC_UNUSED(pluginType); //only used in debug build QCC_UNUSED(mode); //only used in debug build QCC_UNUSED(argc); //only used in debug build QCC_UNUSED(argn); //only used in debug build QCC_UNUSED(argv); //only used in debug build QCC_UNUSED(saved); //only used in debug build QCC_DbgTrace(("%s(pluginType=%s,npp=%p,mode=%u,argc=%d,argn=%p,argv=%p,saved=%p)", __FUNCTION__, pluginType, npp, mode, argc, argn, argv, saved)); #if !defined(NDEBUG) for (int16_t i = 0; i < argc; ++i) { QCC_DbgTrace(("%s=%s", argn[i], argv[i])); if (!strcmp("debug", argn[i])) { QCC_SetLogLevels(argv[i]); } } #endif if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } /* * Example UserAgents: * UserAgent=Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.04 (lucid) Firefox/3.6.23 * Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1 * Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.1 (KHTML, like Gecko) Ubuntu/10.04 Chromium/14.0.835.202 Chrome/14.0.835.202 Safari/535.1 */ QCC_DbgTrace(("UserAgent=%s", NPN_UserAgent(npp))); Plugin plugin(npp); QStatus status = plugin->Initialize(); if (ER_OK == status) { npp->pdata = new PluginData(plugin); return NPERR_NO_ERROR; } else { return NPERR_GENERIC_ERROR; } } NPError NPP_Destroy(NPP npp, NPSavedData** save) { QCC_UNUSED(save); //only used in debug build QCC_DbgTrace(("%s(npp=%p,save=%p)", __FUNCTION__, npp, save)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } delete reinterpret_cast(npp->pdata); npp->pdata = 0; QCC_DbgTrace(("-%s", __FUNCTION__)); return NPERR_NO_ERROR; } NPError NPP_SetWindow(NPP npp, NPWindow* window) { QCC_UNUSED(window); QCC_DbgTrace(("%s", __FUNCTION__)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } return NPERR_NO_ERROR; } NPError NPP_NewStream(NPP npp, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype) { QCC_UNUSED(type); //only used in debug build QCC_UNUSED(stream); //only used in debug build QCC_UNUSED(seekable); //only used in debug build QCC_DbgTrace(("%s(npp=%p,type=%s,stream={url=%s,end=%u,lastmodified=%u,notifyData=%p,headers=%s},seekable=%d,stype=%p)", __FUNCTION__, npp, type, stream->url, stream->end, stream->lastmodified, stream->notifyData, stream->headers, seekable, stype)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } //*stype = NP_ASFILEONLY; // TODO May be able to do this workaround for chrome local files, but it will copy the whole file *stype = NP_NORMAL; return NPERR_NO_ERROR; } NPError NPP_DestroyStream(NPP npp, NPStream* stream, NPReason reason) { QCC_UNUSED(reason); //only used in debug build QCC_DbgTrace(("%s(npp=%p,stream={url=%s,notifyData=%p},reason=%d)", __FUNCTION__, npp, stream->url, stream->notifyData, reason)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } qcc::SocketFd streamFd = reinterpret_cast(stream->notifyData); qcc::Close(streamFd); return NPERR_NO_ERROR; } int32_t NPP_WriteReady(NPP npp, NPStream* stream) { //QCC_DbgTrace(("%s(npp=%p,stream={url=%s,notifyData=%p})", __FUNCTION__, npp, stream->url, stream->notifyData)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } #if defined(QCC_OS_GROUP_WINDOWS) return NP_MAXREADY; #else /* TODO Chrome doesn't correctly support returning 0. */ int32_t numReady; qcc::SocketFd streamFd = reinterpret_cast(stream->notifyData); fd_set writefds; FD_ZERO(&writefds); FD_SET(streamFd, &writefds); struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; int ret = select(streamFd + 1, NULL, &writefds, NULL, &timeout); if (-1 != ret) { numReady = FD_ISSET(streamFd, &writefds) ? MAXREADY : 0; } else { QCC_LogError(ER_OS_ERROR, ("%d - %s", errno, strerror(errno))); numReady = 0; } //QCC_DbgTrace(("%s()=%d", __FUNCTION__, numReady)); return numReady; #endif } int32_t NPP_Write(NPP npp, NPStream* stream, int32_t offset, int32_t len, void* buffer) { QCC_UNUSED(offset); //only used in debug build QCC_DbgTrace(("%s(npp=%p,stream={url=%s,notifyData=%p},offset=%d,len=%d,buffer=%p)", __FUNCTION__, npp, stream->url, stream->notifyData, offset, len, buffer)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } #if defined(QCC_OS_GROUP_WINDOWS) return NP_MAXREADY; #else /* * Under posix, qcc::Send() always blocks. That is a no-no here, so use platform-specific code * to do the correct non-blocking write. */ qcc::SocketFd streamFd = reinterpret_cast(stream->notifyData); int32_t numSent; int ret = send(static_cast(streamFd), buffer, len, MSG_NOSIGNAL); if (-1 != ret) { numSent = ret; } else if (EAGAIN == errno) { numSent = 0; } else { QCC_LogError(ER_OS_ERROR, ("%d - %s", errno, strerror(errno))); numSent = -1; } /* TODO Chrome doesn't correctly support returning 0. */ QCC_DbgTrace(("%s()=%d", __FUNCTION__, numSent)); return numSent; #endif } void NPP_StreamAsFile(NPP npp, NPStream* stream, const char* fname) { QCC_UNUSED(stream); //only used in debug build QCC_UNUSED(fname); //only used in debug build QCC_DbgTrace(("%s(npp=%p,stream=%p,fname=%s)", __FUNCTION__, npp, stream, fname)); if (!npp) { return; } } void NPP_Print(NPP npp, NPPrint* platformPrint) { QCC_UNUSED(platformPrint); QCC_DbgTrace(("%s", __FUNCTION__)); if (!npp) { return; } } int16_t NPP_HandleEvent(NPP npp, void* evt) { QCC_UNUSED(evt); QCC_DbgTrace(("%s", __FUNCTION__)); if (!npp) { return 0; } return 0; } void NPP_URLNotify(NPP npp, const char* url, NPReason reason, void* notifyData) { QCC_UNUSED(url); //only used in debug build QCC_UNUSED(reason); //only used in debug build QCC_UNUSED(notifyData); //only used in debug build QCC_DbgTrace(("%s(npp=%p,url=%s,reason=%d,notifyData=%p)", __FUNCTION__, npp, url, reason, notifyData)); if (!npp) { return; } } NPError NPP_GetValue(NPP npp, NPPVariable var, void* value) { int variable = var; switch (variable) { #if !defined(NDEBUG) case NPPVpluginNameString: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginNameString")); break; case NPPVpluginDescriptionString: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginDescriptionString")); break; case NPPVpluginWindowBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWindowBool")); break; case NPPVpluginTransparentBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginTransparentBool")); break; case NPPVjavaClass: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVjavaClass")); break; case NPPVpluginWindowSize: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWindowSize")); break; case NPPVpluginTimerInterval: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginTimerInterval")); break; case NPPVpluginScriptableInstance: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginScriptableInstance")); break; case NPPVpluginScriptableIID: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginScriptableIID")); break; case NPPVjavascriptPushCallerBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVjavascriptPushCallerBool")); break; case NPPVpluginKeepLibraryInMemory: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginKeepLibraryInMemory")); break; case NPPVpluginNeedsXEmbed: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginNeedsXEmbed")); break; case NPPVpluginScriptableNPObject: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginScriptableNPObject")); break; case NPPVformValue: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVformValue")); break; case NPPVpluginUrlRequestsDisplayedBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginUrlRequestsDisplayedBool")); break; case NPPVpluginWantsAllNetworkStreams: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWantsAllNetworkStreams")); break; #ifdef XP_MACOSX case NPPVpluginDrawingModel: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginDrawingModel")); break; #endif #if (MOZ_PLATFORM_MAEMO == 5) case NPPVpluginWindowlessLocalBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWindowlessLocalBool")); break; #endif #endif // !NDEBUG default: QCC_DbgTrace(("%s(variable=%d)", __FUNCTION__, variable)); break; } NPError ret = NPERR_NO_ERROR; switch (variable) { #if defined(XP_UNIX) case NPPVpluginNeedsXEmbed: *((PRBool*)value) = PR_TRUE; break; #endif case NPPVpluginScriptableNPObject: { if (!npp) { ret = NPERR_INVALID_INSTANCE_ERROR; break; } PluginData* pluginData = reinterpret_cast(npp->pdata); if (!pluginData) { ret = NPERR_GENERIC_ERROR; break; } *(NPObject** )value = pluginData->GetScriptableObject(); break; } default: ret = NPERR_GENERIC_ERROR; break; } return ret; } NPError NPP_SetValue(NPP npp, NPNVariable variable, void* value) { QCC_UNUSED(variable); QCC_UNUSED(value); QCC_DbgTrace(("%s", __FUNCTION__)); if (!npp) { return NPERR_INVALID_INSTANCE_ERROR; } return NPERR_NO_ERROR; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/SocketFdHost.cc0000644000175000017500000001041212620747066022557 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SocketFdHost.h" #include "CallbackNative.h" #include "TypeMapping.h" #include #include #ifndef PRIi64 #define __STDC_FORMAT_MACROS #include #endif #define QCC_MODULE "ALLJOYN_JS" bool _SocketFdHost::send(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String url; NPError ret; qcc::SocketFd streamFd = qcc::INVALID_SOCKET_FD; NPVariant nplength = NPVARIANT_VOID; bool ignored; size_t length; uint8_t* buf = NULL; size_t i; size_t sent = 0; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } if (NPVARIANT_IS_STRING(args[0])) { url = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } QCC_DbgTrace(("url=%s", url.c_str())); status = qcc::SocketDup(socketFd, streamFd); if (ER_OK != status) { QCC_LogError(status, ("SocketDup failed")); goto exit; } ret = NPN_GetURLNotify(plugin->npp, url.c_str(), NULL, reinterpret_cast(streamFd)); if (NPERR_NO_ERROR == ret) { streamFd = qcc::INVALID_SOCKET_FD; /* NPN stream now owns the FD. */ } else { status = ER_FAIL; QCC_LogError(status, ("NPN_GetURLNotify failed - %d", ret)); goto exit; } VOID_TO_NPVARIANT(*result); } else { if (!NPVARIANT_IS_OBJECT(args[0]) || !NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("length"), &nplength) || !(NPVARIANT_IS_INT32(nplength) || NPVARIANT_IS_DOUBLE(nplength))) { plugin->RaiseTypeError("argument 0 is not an array"); typeError = true; goto exit; } length = ToLong(plugin, nplength, ignored); buf = new uint8_t[length]; for (i = 0; i < length; ++i) { NPVariant npelem = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetIntIdentifier(i), &npelem)) { plugin->RaiseTypeError("get array element failed"); typeError = true; goto exit; } buf[i] = ToOctet(plugin, npelem, typeError); NPN_ReleaseVariantValue(&npelem); if (typeError) { plugin->RaiseTypeError("array element is not a number"); goto exit; } } status = qcc::Send(socketFd, buf, length, sent); if (ER_OK != status) { goto exit; } ToUnsignedLong(plugin, sent, *result); } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status, url); callbackNative = NULL; } delete callbackNative; delete[] buf; NPN_ReleaseVariantValue(&nplength); if (qcc::INVALID_SOCKET_FD != streamFd) { qcc::Close(streamFd); } VOID_TO_NPVARIANT(*result); return !typeError; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/Plugin.cc0000644000175000017500000001355412620747066021467 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Plugin.h" #include "TypeMapping.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" QStatus _Plugin::Initialize() { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; NPObject* pluginElement = NULL; NPVariant variant = NPVARIANT_VOID; const char* strictEquals = "(function () { return function(a, b) { return a === b; } })();"; NPString script = { strictEquals, (uint32_t)strlen(strictEquals) }; NPError ret; ret = NPN_GetValue(npp, NPNVPluginElementNPObject, &pluginElement); if (NPERR_NO_ERROR != ret) { status = ER_FAIL; QCC_LogError(status, ("Get PluginElementNPObject failed - %d", ret)); goto exit; } /* * The below doesn't work on recent chrome: http://code.google.com/p/chromium/issues/detail?id=129570. * StrictEquals falls back to pointer comparison, which does work (at least for chrome). */ if (!NPN_Evaluate(npp, pluginElement, &script, &variant)) { status = ER_FAIL; QCC_LogError(status, ("Evaluate failed")); goto exit; } if (NPVARIANT_IS_OBJECT(variant) && !NPN_SetProperty(npp, pluginElement, NPN_GetStringIdentifier("strictEquals"), &variant)) { status = ER_FAIL; QCC_LogError(status, ("Set strictEquals failed")); goto exit; } exit: NPN_ReleaseVariantValue(&variant); if (pluginElement) { NPN_ReleaseObject(pluginElement); } return status; } QStatus _Plugin::Origin(qcc::String& origin) { QStatus status = ER_OK; bool typeError = false; NPObject* window = NULL; NPVariant location = NPVARIANT_VOID; NPVariant protocol = NPVARIANT_VOID; NPVariant hostname = NPVARIANT_VOID; NPVariant port = NPVARIANT_VOID; NPVariant document = NPVARIANT_VOID; NPVariant domain = NPVARIANT_VOID; if (NPERR_NO_ERROR == NPN_GetValue(npp, NPNVWindowNPObject, &window) && NPN_GetProperty(npp, window, NPN_GetStringIdentifier("location"), &location) && NPVARIANT_IS_OBJECT(location) && NPN_GetProperty(npp, NPVARIANT_TO_OBJECT(location), NPN_GetStringIdentifier("protocol"), &protocol) && NPN_GetProperty(npp, NPVARIANT_TO_OBJECT(location), NPN_GetStringIdentifier("hostname"), &hostname) && NPN_GetProperty(npp, NPVARIANT_TO_OBJECT(location), NPN_GetStringIdentifier("port"), &port) && NPN_GetProperty(npp, window, NPN_GetStringIdentifier("document"), &document) && NPVARIANT_IS_OBJECT(document) && NPN_GetProperty(npp, NPVARIANT_TO_OBJECT(document), NPN_GetStringIdentifier("domain"), &domain)) { Plugin plugin = Plugin::wrap(this); qcc::String protocolString, hostnameString, portString; protocolString = ToDOMString(plugin, protocol, typeError) + "//"; if (typeError) { status = ER_FAIL; QCC_LogError(status, ("get location.protocol failed")); goto exit; } if (NPVARIANT_IS_STRING(domain)) { hostnameString = ToDOMString(plugin, domain, typeError); } else { hostnameString = ToDOMString(plugin, hostname, typeError); } if (typeError) { status = ER_FAIL; QCC_LogError(status, ("get location.hostname or document.domain failed")); goto exit; } portString = ToDOMString(plugin, port, typeError); if (typeError) { status = ER_FAIL; QCC_LogError(status, ("get location.port failed")); goto exit; } origin = protocolString + hostnameString + (portString.empty() ? "" : ":") + portString; } else { status = ER_FAIL; QCC_LogError(status, ("get location or document.domain failed")); goto exit; } exit: NPN_ReleaseVariantValue(&domain); NPN_ReleaseVariantValue(&document); NPN_ReleaseVariantValue(&port); NPN_ReleaseVariantValue(&hostname); NPN_ReleaseVariantValue(&protocol); NPN_ReleaseVariantValue(&location); NPN_ReleaseObject(window); return status; } bool _Plugin::StrictEquals(const NPVariant& a, const NPVariant& b) const { bool equals = false; if (npp) { NPObject* pluginElement = NULL; NPVariant result = NPVARIANT_VOID; NPError error = NPN_GetValue(npp, NPNVPluginElementNPObject, &pluginElement); if (NPERR_NO_ERROR == error) { NPVariant args[] = { a, b }; if (NPN_Invoke(npp, pluginElement, NPN_GetStringIdentifier("strictEquals"), args, 2, &result) && NPVARIANT_IS_BOOLEAN(result)) { equals = NPVARIANT_TO_BOOLEAN(result); } else { QCC_LogError(ER_WARNING, ("NPN_Invoke(strictEquals) failed, falling back to pointer comparison")); equals = NPVARIANT_TO_OBJECT(a) == NPVARIANT_TO_OBJECT(b); } } else { QCC_LogError(ER_FAIL, ("NPN_GetValue()=%d", error)); } NPN_ReleaseVariantValue(&result); if (pluginElement) { NPN_ReleaseObject(pluginElement); } } return equals; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/np.cc0000644000175000017500000002043712620747066020644 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "npn.h" #include "PluginData.h" #include #include #include #include #include #include #include extern NPNetscapeFuncs* npn; #define QCC_MODULE "ALLJOYN_JS" /* This is only defined for XP_UNIX platforms in the Gecko SDK. */ #if !defined(NP_EXPORT) #define NP_EXPORT(__type) __type #endif /* This is not defined under Android. */ #if !defined(OSCALL) #define OSCALL #endif /* * Different browsers call the exported functions in different orders, so the NP_ calls are littered * with this call. */ static void Initialize() { if (AllJoynInit() != ER_OK) { return; } #ifdef ROUTER if (AllJoynRouterInit() != ER_OK) { AllJoynShutdown(); return; } #endif QCC_UseOSLogging(true); QCC_SetLogLevels("ALLJOYN_JS=15"); } static void Shutdown() { #ifdef ROUTER AllJoynRouterShutdown(); #endif AllJoynShutdown(); } static NPError InitializePluginFuncs(NPPluginFuncs* pFuncs) { if (!pFuncs) { QCC_LogError(ER_FAIL, ("Null NPPluginFuncs - NPERR_INVALID_FUNCTABLE_ERROR")); return NPERR_INVALID_FUNCTABLE_ERROR; } pFuncs->size = sizeof(NPPluginFuncs); pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->javaClass = 0; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; return NPERR_NO_ERROR; } static NPError InitializeNetscapeFuncs(NPNetscapeFuncs* bFuncs) { if (!bFuncs) { QCC_LogError(ER_FAIL, ("Null NPNetscapeFuncs - NPERR_INVALID_FUNCTABLE_ERROR")); return NPERR_INVALID_FUNCTABLE_ERROR; } if (((bFuncs->version >> 8) & 0xff) > NP_VERSION_MAJOR) { QCC_LogError(ER_FAIL, ("Incompatible version %d > %d - NPERR_INCOMPATIBLE_VERSION_ERROR", (bFuncs->version >> 8) & 0xff, NP_VERSION_MAJOR)); return NPERR_INCOMPATIBLE_VERSION_ERROR; } if (bFuncs->size < sizeof(NPNetscapeFuncs)) { QCC_LogError(ER_FAIL, ("NPNetscapeFuncs unexpected size %d < %d - NPERR_GENERIC_ERROR", bFuncs->size, sizeof(NPNetscapeFuncs))); return NPERR_GENERIC_ERROR; } npn = (NPNetscapeFuncs*) malloc(sizeof(NPNetscapeFuncs)); memcpy(npn, bFuncs, sizeof(NPNetscapeFuncs)); return NPERR_NO_ERROR; } extern "C" { NP_EXPORT(char*) NP_GetPluginVersion() { Initialize(); QCC_DbgPrintf(("%s", __FUNCTION__)); return const_cast("15.09.00a"); } NP_EXPORT(char*) NP_GetMIMEDescription() { Initialize(); QCC_DbgPrintf(("%s", __FUNCTION__)); /* * Be wary of changing this. It appears that Android requires a non-empty description field. */ return const_cast("application/x-alljoyn::AllJoyn"); } NP_EXPORT(NPError) OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { Initialize(); QCC_DbgPrintf(("%s", __FUNCTION__)); return InitializePluginFuncs(pFuncs); } #if defined(QCC_OS_GROUP_WINDOWS) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { gHinstance = hinstDLL; return TRUE; } NP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs) { Initialize(); PluginData::InitializeStaticData(); gPluginThread = qcc::Thread::GetThread(); QCC_DbgPrintf(("%s", __FUNCTION__)); return InitializeNetscapeFuncs(bFuncs); } #else NP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs) { Initialize(); PluginData::InitializeStaticData(); gPluginThread = qcc::Thread::GetThread(); QCC_DbgPrintf(("%s", __FUNCTION__)); NPError ret; ret = InitializeNetscapeFuncs(bFuncs); if (NPERR_NO_ERROR != ret) { return ret; } ret = InitializePluginFuncs(pFuncs); if (NPERR_NO_ERROR != ret) { return ret; } return ret; } #endif NP_EXPORT(NPError) OSCALL NP_Shutdown() { QCC_DbgPrintf(("%s", __FUNCTION__)); qcc::Thread::CleanExternalThreads(); PluginData::DumpNPObjects(); Shutdown(); return NPERR_NO_ERROR; } NP_EXPORT(NPError) OSCALL NP_GetValue(void* future, NPPVariable variable, void* value) { QCC_UNUSED(future); Initialize(); switch (variable) { #if !defined(NDEBUG) case NPPVpluginNameString: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginNameString")); break; case NPPVpluginDescriptionString: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginDescriptionString")); break; case NPPVpluginWindowBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWindowBool")); break; case NPPVpluginTransparentBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginTransparentBool")); break; case NPPVjavaClass: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVjavaClass")); break; case NPPVpluginWindowSize: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWindowSize")); break; case NPPVpluginTimerInterval: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginTimerInterval")); break; case NPPVpluginScriptableInstance: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginScriptableInstance")); break; case NPPVpluginScriptableIID: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginScriptableIID")); break; case NPPVjavascriptPushCallerBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVjavascriptPushCallerBool")); break; case NPPVpluginKeepLibraryInMemory: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginKeepLibraryInMemory")); break; case NPPVpluginNeedsXEmbed: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginNeedsXEmbed")); break; case NPPVpluginScriptableNPObject: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginScriptableNPObject")); break; case NPPVformValue: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVformValue")); break; case NPPVpluginUrlRequestsDisplayedBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginUrlRequestsDisplayedBool")); break; case NPPVpluginWantsAllNetworkStreams: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWantsAllNetworkStreams")); break; #ifdef XP_MACOSX case NPPVpluginDrawingModel: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginDrawingModel")); break; #endif #if (MOZ_PLATFORM_MAEMO == 5) case NPPVpluginWindowlessLocalBool: QCC_DbgTrace(("%s(variable=%s)", __FUNCTION__, "NPPVpluginWindowlessLocalBool")); break; #endif #endif // !NDEBUG default: QCC_DbgTrace(("%s(variable=%d)", __FUNCTION__, variable)); break; } NPError ret = NPERR_NO_ERROR; switch (variable) { case NPPVpluginNameString: *((const char** )value) = "AllJoyn"; break; case NPPVpluginDescriptionString: *((const char** )value) = "AllJoyn browser plugin"; break; default: ret = NPERR_GENERIC_ERROR; break; } return ret; } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/TypeMapping.cc0000644000175000017500000015102112620747066022456 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "TypeMapping.h" #include "NativeObject.h" #include "SignatureUtils.h" #include "SocketFdHost.h" #include #include #include #include #ifndef PRIi64 #define __STDC_FORMAT_MACROS #include #endif #define QCC_MODULE "ALLJOYN_JS" #ifndef NAN /* * From http://msdn.microsoft.com/en-us/library/w22adx1s(v=vs.80).aspx */ static const unsigned long __nan[2] = { 0xffffffff, 0x7fffffff }; #define NAN (*(const double*)__nan); #endif static bool IsPrimitive(const NPVariant& value) { return (value.type != NPVariantType_Object); } typedef enum { HINT_STRING, HINT_NUMBER } Hint; /** * @return the default value. This must be released by the caller. */ static NPVariant DefaultValue(Plugin& plugin, NPObject* object, Hint hint, bool& typeError) { typeError = false; int step = (hint == HINT_NUMBER) ? 1 : 2; while (0 < step && step < 3) { switch (step) { case 1: { NPVariant val; if (NPN_Invoke(plugin->npp, object, NPN_GetStringIdentifier("valueOf"), 0, 0, &val)) { if (IsPrimitive(val)) { return val; } else { NPN_ReleaseVariantValue(&val); } } break; } case 2: { NPVariant str; if (NPN_Invoke(plugin->npp, object, NPN_GetStringIdentifier("toString"), 0, 0, &str)) { if (IsPrimitive(str)) { return str; } else { NPN_ReleaseVariantValue(&str); } } break; } } step += (hint == HINT_NUMBER) ? 1 : -1; } typeError = true; NPVariant undefined = NPVARIANT_VOID; return undefined; } /** * @return the primitive value. This must be released by the caller. */ static NPVariant ToPrimitive(Plugin& plugin, const NPVariant& value, Hint hint, bool& typeError) { if (IsPrimitive(value)) { return value; } else { assert(NPVARIANT_IS_OBJECT(value)); return DefaultValue(plugin, NPVARIANT_TO_OBJECT(value), hint, typeError); } } bool ToBoolean(Plugin& plugin, const NPVariant& value, bool& typeError) { QCC_UNUSED(plugin); typeError = false; switch (value.type) { case NPVariantType_Void: case NPVariantType_Null: return false; case NPVariantType_Bool: return NPVARIANT_TO_BOOLEAN(value); case NPVariantType_Int32: return (NPVARIANT_TO_INT32(value) != 0); case NPVariantType_Double: return !(fpclassify(NPVARIANT_TO_DOUBLE(value)) & (FP_NAN | FP_ZERO)); case NPVariantType_String: return NPVARIANT_TO_STRING(value).UTF8Length != 0; case NPVariantType_Object: return true; default: assert(0); /* Will not reach here. */ return false; } } static double ToNumber(Plugin& plugin, const NPVariant& value, bool& typeError) { switch (value.type) { case NPVariantType_Void: return NAN; case NPVariantType_Null: return +0; case NPVariantType_Bool: return (NPVARIANT_TO_BOOLEAN(value) ? 1 : 0); case NPVariantType_Int32: return NPVARIANT_TO_INT32(value); case NPVariantType_Double: return NPVARIANT_TO_DOUBLE(value); case NPVariantType_String: { double n = NAN; NPObject* window = NULL; if (NPERR_NO_ERROR == NPN_GetValue(plugin->npp, NPNVWindowNPObject, &window)) { NPVariant result; if (NPN_Invoke(plugin->npp, window, NPN_GetStringIdentifier("parseFloat"), &value, 1, &result)) { if (NPVARIANT_IS_INT32(result)) { n = NPVARIANT_TO_INT32(result); } else if (NPVARIANT_IS_DOUBLE(result)) { n = NPVARIANT_TO_DOUBLE(result); } NPN_ReleaseVariantValue(&result); } NPN_ReleaseObject(window); } return n; } case NPVariantType_Object: { NPVariant primitive = ToPrimitive(plugin, value, HINT_NUMBER, typeError); if (!typeError) { return ToNumber(plugin, primitive, typeError); } NPN_ReleaseVariantValue(&primitive); return NAN; } default: assert(0); /* Will not reach here. */ return NAN; } } /* * Unlike many other programming languages JavaScript is not a typed language. * In JavaScript numbers are always stored as double precision floating point numbers * we must read the double and cast it to the Integer type desired. */ template T ToInteger(Plugin& plugin, const NPVariant& value, bool& typeError) { double n = ToNumber(plugin, value, typeError); if (fpclassify(n) & (FP_NAN | FP_ZERO | FP_INFINITE)) { return +0; } return static_cast(n); } /** * The JavaScript Number.toString() function. * * Why use this? The JavaScript specifies a particular algorithm for converting numbers to strings * that is not the same as printf(). This is used to ensure that the coercion done here is * identical to that done by JavaScript. */ static qcc::String NumberToString(Plugin& plugin, double value) { qcc::String s("NaN"); NPObject* window = NULL; if (NPERR_NO_ERROR == NPN_GetValue(plugin->npp, NPNVWindowNPObject, &window)) { char numberToString[50]; snprintf(numberToString, 50, "new Number(%.16e).toString();", value); NPString script = { numberToString, (uint32_t)strlen(numberToString) }; NPVariant variant = NPVARIANT_VOID; if (NPN_Evaluate(plugin->npp, window, &script, &variant) && NPVARIANT_IS_STRING(variant) && NPVARIANT_TO_STRING(variant).UTF8Length) { s = qcc::String(NPVARIANT_TO_STRING(variant).UTF8Characters, NPVARIANT_TO_STRING(variant).UTF8Length); } else { QCC_LogError(ER_FAIL, ("new Number().toString() failed")); } NPN_ReleaseVariantValue(&variant); NPN_ReleaseObject(window); } return s; } static qcc::String ToString(Plugin& plugin, const NPVariant& value, bool& typeError) { switch (value.type) { case NPVariantType_Void: return "undefined"; case NPVariantType_Null: return "null"; case NPVariantType_Bool: return NPVARIANT_TO_BOOLEAN(value) ? "true" : "false"; case NPVariantType_Int32: return NumberToString(plugin, NPVARIANT_TO_INT32(value)); case NPVariantType_Double: return NumberToString(plugin, NPVARIANT_TO_DOUBLE(value)); case NPVariantType_String: return NPVARIANT_TO_STRING(value).UTF8Length ? qcc::String(NPVARIANT_TO_STRING(value).UTF8Characters, NPVARIANT_TO_STRING(value).UTF8Length) : qcc::String(); case NPVariantType_Object: { NPVariant primitive = ToPrimitive(plugin, value, HINT_STRING, typeError); if (!typeError) { return ToString(plugin, primitive, typeError); } NPN_ReleaseVariantValue(&primitive); return "undefined"; } default: assert(0); /* Will not reach here. */ return qcc::String(); } } static void ToDictionaryKey(Plugin& plugin, const ajn::MsgArg& value, NPIdentifier& identifier) { char str[32]; switch (value.typeId) { case ajn::ALLJOYN_BYTE: snprintf(str, 32, "%u", value.v_byte); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_BOOLEAN: identifier = NPN_GetStringIdentifier(value.v_bool ? "true" : "false"); break; case ajn::ALLJOYN_INT16: snprintf(str, 32, "%d", value.v_int16); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_UINT16: snprintf(str, 32, "%u", value.v_uint16); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_INT32: snprintf(str, 32, "%d", value.v_int32); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_UINT32: snprintf(str, 32, "%u", value.v_uint32); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_INT64: snprintf(str, 32, "%" PRIi64, value.v_int64); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_UINT64: snprintf(str, 32, "%" PRIu64, value.v_uint64); identifier = NPN_GetStringIdentifier(str); break; case ajn::ALLJOYN_DOUBLE: { qcc::String str = NumberToString(plugin, value.v_double); identifier = NPN_GetStringIdentifier(str.c_str()); break; } case ajn::ALLJOYN_STRING: identifier = NPN_GetStringIdentifier(value.v_string.str); break; case ajn::ALLJOYN_OBJECT_PATH: identifier = NPN_GetStringIdentifier(value.v_objPath.str); break; case ajn::ALLJOYN_SIGNATURE: identifier = NPN_GetStringIdentifier(value.v_signature.sig); break; case ajn::ALLJOYN_HANDLE: switch (sizeof(qcc::SocketFd)) { case 4: snprintf(str, 32, "%d", (int32_t)value.v_handle.fd); identifier = NPN_GetStringIdentifier(str); break; case 8: snprintf(str, 32, "%" PRIi64, (int64_t)value.v_handle.fd); identifier = NPN_GetStringIdentifier(str); break; } break; default: /* This should not make it through the AllJoyn core. */ assert(0); QCC_LogError(ER_FAIL, ("Unhandled MsgArg type: 0x%x", value.typeId)); break; } } bool NewObject(Plugin& plugin, NPVariant& variant) { NPObject* window = NULL; if (NPERR_NO_ERROR == NPN_GetValue(plugin->npp, NPNVWindowNPObject, &window)) { NPString script = { "new Object();", (uint32_t)strlen("new Object();") }; bool evaluated = NPN_Evaluate(plugin->npp, window, &script, &variant); NPN_ReleaseObject(window); bool success = (evaluated && NPVARIANT_IS_OBJECT(variant)); if (!success) { QCC_LogError(ER_FAIL, ("new Object() failed")); } return success; } VOID_TO_NPVARIANT(variant); return false; } bool NewArray(Plugin& plugin, NPVariant& variant) { NPObject* window = NULL; if (NPERR_NO_ERROR == NPN_GetValue(plugin->npp, NPNVWindowNPObject, &window)) { NPString script = { "new Array();", (uint32_t)strlen("new Array();") }; bool evaluated = NPN_Evaluate(plugin->npp, window, &script, &variant); NPN_ReleaseObject(window); bool success = (evaluated && NPVARIANT_IS_OBJECT(variant)); if (!success) { QCC_LogError(ER_FAIL, ("new Array() failed")); } return success; } VOID_TO_NPVARIANT(variant); return false; } /** * @param signature a complete type signature. */ void ToAny(Plugin& plugin, const NPVariant& value, const qcc::String signature, ajn::MsgArg& arg, bool& typeError) { typeError = false; QStatus status = ER_OK; switch (signature[0]) { case ajn::ALLJOYN_BOOLEAN: status = arg.Set("b", ToBoolean(plugin, value, typeError)); break; case ajn::ALLJOYN_BYTE: status = arg.Set("y", ToOctet(plugin, value, typeError)); break; case ajn::ALLJOYN_INT16: status = arg.Set("n", ToShort(plugin, value, typeError)); break; case ajn::ALLJOYN_UINT16: status = arg.Set("q", ToUnsignedShort(plugin, value, typeError)); break; case ajn::ALLJOYN_INT32: status = arg.Set("i", ToLong(plugin, value, typeError)); break; case ajn::ALLJOYN_UINT32: status = arg.Set("u", ToUnsignedLong(plugin, value, typeError)); break; case ajn::ALLJOYN_INT64: { int64_t x = ToLongLong(plugin, value, typeError); status = arg.Set("x", x); break; } case ajn::ALLJOYN_UINT64: { uint64_t t = ToUnsignedLongLong(plugin, value, typeError); status = arg.Set("t", t); break; } case ajn::ALLJOYN_DOUBLE: { double d = ToDouble(plugin, value, typeError); status = arg.Set("d", d); break; } case ajn::ALLJOYN_STRING: { qcc::String s = ToDOMString(plugin, value, typeError); status = arg.Set("s", s.c_str()); arg.Stabilize(); break; } case ajn::ALLJOYN_OBJECT_PATH: { qcc::String o = ToDOMString(plugin, value, typeError); status = arg.Set("o", o.c_str()); arg.Stabilize(); break; } case ajn::ALLJOYN_SIGNATURE: { qcc::String g = ToDOMString(plugin, value, typeError); status = arg.Set("g", g.c_str()); arg.Stabilize(); break; } case ajn::ALLJOYN_STRUCT_OPEN: { if (!NPVARIANT_IS_OBJECT(value)) { typeError = true; break; } NPVariant length = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("length"), &length) || !(NPVARIANT_IS_INT32(length) || NPVARIANT_IS_DOUBLE(length))) { NPN_ReleaseVariantValue(&length); typeError = true; break; } bool ignored; size_t numMembers = ToLong(plugin, length, ignored); NPN_ReleaseVariantValue(&length); qcc::String substr = signature.substr(1, signature.size() - 1); if (numMembers != ajn::SignatureUtils::CountCompleteTypes(substr.c_str())) { typeError = true; break; } arg.typeId = ajn::ALLJOYN_STRUCT; arg.v_struct.numMembers = numMembers; arg.v_struct.members = new ajn::MsgArg[arg.v_struct.numMembers]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsArgs); const char* begin = signature.c_str() + 1; for (size_t i = 0; i < arg.v_struct.numMembers; ++i) { const char* end = begin; status = ajn::SignatureUtils::ParseCompleteType(end); if (ER_OK != status) { break; } qcc::String typeSignature(begin, end - begin); NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } ToAny(plugin, element, typeSignature, arg.v_struct.members[i], typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } begin = end; } break; } case ajn::ALLJOYN_ARRAY: { if (!NPVARIANT_IS_OBJECT(value)) { typeError = true; break; } qcc::String elemSignature = signature.substr(1); if (elemSignature[0] == ajn::ALLJOYN_DICT_ENTRY_OPEN) { const char* begin = elemSignature.c_str() + 1; const char* end = begin; status = ajn::SignatureUtils::ParseCompleteType(end); if (ER_OK != status) { break; } qcc::String keySignature(begin, end - begin); begin = end; status = ajn::SignatureUtils::ParseCompleteType(end); if (ER_OK != status) { break; } qcc::String valueSignature(begin, end - begin); NPIdentifier* properties = NULL; uint32_t propertiesCount = 0; if (!NPN_Enumerate(plugin->npp, NPVARIANT_TO_OBJECT(value), &properties, &propertiesCount)) { typeError = true; break; } size_t numElements = propertiesCount; ajn::MsgArg* elements = new ajn::MsgArg[numElements]; arg.v_array.SetElements(elemSignature.c_str(), numElements, elements); if (ER_OK != status) { NPN_MemFree(properties); delete[] elements; break; } arg.typeId = ajn::ALLJOYN_ARRAY; arg.SetOwnershipFlags(ajn::MsgArg::OwnsArgs); for (size_t i = 0; i < numElements; ++i) { NPVariant key; if (NPN_IdentifierIsString(properties[i])) { NPUTF8* utf8 = NPN_UTF8FromIdentifier(properties[i]); ToDOMString(plugin, utf8, strlen(utf8), key); NPN_MemFree(utf8); } else { int32_t n = NPN_IntFromIdentifier(properties[i]); INT32_TO_NPVARIANT(n, key); } NPVariant val; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), properties[i], &val)) { typeError = true; break; } elements[i].typeId = ajn::ALLJOYN_DICT_ENTRY; elements[i].v_dictEntry.key = new ajn::MsgArg(); elements[i].v_dictEntry.val = new ajn::MsgArg(); elements[i].SetOwnershipFlags(ajn::MsgArg::OwnsArgs); ToAny(plugin, key, keySignature, *elements[i].v_dictEntry.key, typeError); if (!typeError) { ToAny(plugin, val, valueSignature, *elements[i].v_dictEntry.val, typeError); } NPN_ReleaseVariantValue(&val); NPN_ReleaseVariantValue(&key); } NPN_MemFree(properties); } else { NPVariant length = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("length"), &length) || !(NPVARIANT_IS_INT32(length) || NPVARIANT_IS_DOUBLE(length))) { NPN_ReleaseVariantValue(&length); typeError = true; break; } bool ignored; size_t numElements = ToLong(plugin, length, ignored); NPN_ReleaseVariantValue(&length); switch (elemSignature[0]) { case ajn::ALLJOYN_BOOLEAN: { arg.typeId = ajn::ALLJOYN_BOOLEAN_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_bool = new bool[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_bool)[i] = ToBoolean(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_BYTE: { arg.typeId = ajn::ALLJOYN_BYTE_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_byte = new uint8_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_byte)[i] = ToOctet(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_INT32: { arg.typeId = ajn::ALLJOYN_INT32_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_int32 = new int32_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_int32)[i] = ToLong(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_INT16: { arg.typeId = ajn::ALLJOYN_INT16_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_int16 = new int16_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_int16)[i] = ToShort(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_UINT16: { arg.typeId = ajn::ALLJOYN_UINT16_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_uint16 = new uint16_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_uint16)[i] = ToUnsignedShort(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_UINT64: { arg.typeId = ajn::ALLJOYN_UINT64_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_uint64 = new uint64_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_uint64)[i] = ToUnsignedLongLong(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_UINT32: { arg.typeId = ajn::ALLJOYN_UINT32_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_uint32 = new uint32_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_uint32)[i] = ToUnsignedLong(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_INT64: { arg.typeId = ajn::ALLJOYN_INT64_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_int64 = new int64_t[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_int64)[i] = ToLongLong(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } case ajn::ALLJOYN_DOUBLE: { arg.typeId = ajn::ALLJOYN_DOUBLE_ARRAY; arg.v_scalarArray.numElements = numElements; arg.v_scalarArray.v_double = new double[numElements]; arg.SetOwnershipFlags(ajn::MsgArg::OwnsData); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } const_cast(arg.v_scalarArray.v_double)[i] = ToDouble(plugin, element, typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } default: { ajn::MsgArg* elements = new ajn::MsgArg[numElements]; status = arg.v_array.SetElements(elemSignature.c_str(), numElements, elements); if (ER_OK != status) { delete[] elements; break; } arg.typeId = ajn::ALLJOYN_ARRAY; arg.SetOwnershipFlags(ajn::MsgArg::OwnsArgs); for (size_t i = 0; i < numElements; ++i) { NPVariant element = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetIntIdentifier(i), &element)) { typeError = true; break; } ToAny(plugin, element, elemSignature, elements[i], typeError); NPN_ReleaseVariantValue(&element); if (typeError) { break; } } break; } } } break; } case ajn::ALLJOYN_VARIANT: { if (!NPVARIANT_IS_OBJECT(value)) { typeError = true; break; } NPIdentifier* properties = NULL; uint32_t propertiesCount = 0; if (!NPN_Enumerate(plugin->npp, NPVARIANT_TO_OBJECT(value), &properties, &propertiesCount)) { typeError = true; break; } if (1 != propertiesCount) { NPN_MemFree(properties); typeError = true; break; } arg.typeId = ajn::ALLJOYN_VARIANT; arg.v_variant.val = new ajn::MsgArg; arg.SetOwnershipFlags(ajn::MsgArg::OwnsArgs); NPUTF8* utf8 = NPN_UTF8FromIdentifier(properties[0]); qcc::String signature(utf8); NPVariant val; if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), properties[0], &val)) { ToAny(plugin, val, signature, *arg.v_variant.val, typeError); NPN_ReleaseVariantValue(&val); } else { typeError = true; } NPN_MemFree(utf8); NPN_MemFree(properties); break; } case ajn::ALLJOYN_HANDLE: { qcc::SocketFd fd = qcc::INVALID_SOCKET_FD; switch (value.type) { case NPVariantType_Void: case NPVariantType_Null: break; case NPVariantType_Bool: typeError = true; break; case NPVariantType_Int32: fd = NPVARIANT_TO_INT32(value); break; case NPVariantType_Double: fd = static_cast(NPVARIANT_TO_DOUBLE(value)); break; case NPVariantType_String: { NPObject* window = NULL; if (NPERR_NO_ERROR == NPN_GetValue(plugin->npp, NPNVWindowNPObject, &window)) { NPVariant result; if (NPN_Invoke(plugin->npp, window, NPN_GetStringIdentifier("parseFloat"), &value, 1, &result)) { if (NPVARIANT_IS_INT32(result)) { fd = NPVARIANT_TO_INT32(result); } else if (NPVARIANT_IS_DOUBLE(result)) { fd = static_cast(NPVARIANT_TO_DOUBLE(result)); } NPN_ReleaseVariantValue(&result); } NPN_ReleaseObject(window); } break; } case NPVariantType_Object: { SocketFdHost* socketFd = ToHostObject(plugin, value, typeError); if (typeError || !socketFd) { typeError = true; break; } fd = (*socketFd)->GetFd(); break; } default: assert(0); /* Will not reach here. */ typeError = true; break; } if (!typeError) { arg.Set("h", fd); } break; } default: status = ER_BUS_BAD_SIGNATURE; break; } if ((ER_OK != status) || typeError) { QCC_LogError(status, ("ToAny failed typeError=%d", typeError)); typeError = true; } } void ToAny(Plugin& plugin, const ajn::MsgArg& value, NPVariant& variant, QStatus& status) { status = ER_OK; switch (value.typeId) { case ajn::ALLJOYN_BOOLEAN: ToBoolean(plugin, value.v_bool, variant); break; case ajn::ALLJOYN_BYTE: ToOctet(plugin, value.v_byte, variant); break; case ajn::ALLJOYN_INT16: ToShort(plugin, value.v_int16, variant); break; case ajn::ALLJOYN_UINT16: ToUnsignedShort(plugin, value.v_uint16, variant); break; case ajn::ALLJOYN_INT32: ToLong(plugin, value.v_int32, variant); break; case ajn::ALLJOYN_UINT32: ToUnsignedLong(plugin, value.v_uint32, variant); break; case ajn::ALLJOYN_INT64: ToLongLong(plugin, value.v_int64, variant); break; case ajn::ALLJOYN_UINT64: ToUnsignedLongLong(plugin, value.v_uint64, variant); break; case ajn::ALLJOYN_DOUBLE: ToDouble(plugin, value.v_double, variant); break; case ajn::ALLJOYN_STRING: ToDOMString(plugin, value.v_string.str, value.v_string.len, variant); break; case ajn::ALLJOYN_OBJECT_PATH: ToDOMString(plugin, value.v_objPath.str, value.v_objPath.len, variant); break; case ajn::ALLJOYN_SIGNATURE: ToDOMString(plugin, value.v_signature.sig, value.v_objPath.len, variant); break; case ajn::ALLJOYN_STRUCT: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_struct.numMembers); ++i) { NPVariant element = NPVARIANT_VOID; ToAny(plugin, value.v_struct.members[i], element, status); if ((ER_OK == status) && !NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_VARIANT: { if (ajn::ALLJOYN_VARIANT != value.v_variant.val->typeId) { ToAny(plugin, *value.v_variant.val, variant, status); } else if (NewObject(plugin, variant)) { qcc::String nestedSignature = value.v_variant.val->v_variant.val->Signature(); NPVariant nestedValue = NPVARIANT_VOID; ToAny(plugin, *value.v_variant.val->v_variant.val, nestedValue, status); if ((ER_OK == status) && !NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetStringIdentifier(nestedSignature.c_str()), &nestedValue)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&nestedValue); } else { status = ER_FAIL; QCC_LogError(status, ("NewObject failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_ARRAY: { if (value.v_array.GetElemSig()[0] == ajn::ALLJOYN_DICT_ENTRY_OPEN) { if (NewObject(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_array.GetNumElements()); ++i) { NPIdentifier key = 0; NPVariant val = NPVARIANT_VOID; ToDictionaryKey(plugin, *value.v_array.GetElements()[i].v_dictEntry.key, key); ToAny(plugin, *value.v_array.GetElements()[i].v_dictEntry.val, val, status); if ((ER_OK == status) && !NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), key, &val)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&val); } } else { status = ER_FAIL; QCC_LogError(status, ("NewObject failed")); VOID_TO_NPVARIANT(variant); } } else { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_array.GetNumElements()); ++i) { NPVariant element = NPVARIANT_VOID; ToAny(plugin, value.v_array.GetElements()[i], element, status); if ((ER_OK == status) && !NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } } break; } case ajn::ALLJOYN_BOOLEAN_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToBoolean(plugin, value.v_scalarArray.v_bool[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_DOUBLE_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToDouble(plugin, value.v_scalarArray.v_double[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_INT32_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToLong(plugin, value.v_scalarArray.v_int32[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_INT16_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToShort(plugin, value.v_scalarArray.v_int16[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_UINT16_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToUnsignedShort(plugin, value.v_scalarArray.v_uint16[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_UINT64_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToUnsignedLongLong(plugin, value.v_scalarArray.v_uint64[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_UINT32_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToUnsignedLong(plugin, value.v_scalarArray.v_uint32[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_INT64_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToLongLong(plugin, value.v_scalarArray.v_int64[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_BYTE_ARRAY: { if (NewArray(plugin, variant)) { for (size_t i = 0; (ER_OK == status) && (i < value.v_scalarArray.numElements); ++i) { NPVariant element = NPVARIANT_VOID; ToOctet(plugin, value.v_scalarArray.v_byte[i], element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &element)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } } else { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); VOID_TO_NPVARIANT(variant); } break; } case ajn::ALLJOYN_HANDLE: { qcc::SocketFd fd; status = qcc::SocketDup(value.v_handle.fd, fd); if (ER_OK == status) { SocketFdHost socketFdHost(plugin, fd); ToHostObject(plugin, socketFdHost, variant); } break; } default: /* Should never reach this case. */ assert(0); QCC_LogError(ER_FAIL, ("Unhandled MsgArg type: 0x%x", value.typeId)); break; } } void ToBoolean(Plugin& plugin, bool value, NPVariant& variant) { QCC_UNUSED(plugin); BOOLEAN_TO_NPVARIANT(value, variant); } uint8_t ToOctet(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; return ToInteger(plugin, value, typeError); } void ToOctet(Plugin& plugin, uint8_t value, NPVariant& variant) { QCC_UNUSED(plugin); INT32_TO_NPVARIANT(value, variant); } int16_t ToShort(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; return ToInteger(plugin, value, typeError); } void ToShort(Plugin& plugin, int16_t value, NPVariant& variant) { QCC_UNUSED(plugin); INT32_TO_NPVARIANT(value, variant); } uint16_t ToUnsignedShort(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; return ToInteger(plugin, value, typeError); } void ToUnsignedShort(Plugin& plugin, uint16_t value, NPVariant& variant) { QCC_UNUSED(plugin); INT32_TO_NPVARIANT(value, variant); } int32_t ToLong(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; return ToInteger(plugin, value, typeError); } void ToLong(Plugin& plugin, int32_t value, NPVariant& variant) { QCC_UNUSED(plugin); INT32_TO_NPVARIANT(value, variant); } uint32_t ToUnsignedLong(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; return ToInteger(plugin, value, typeError); } void ToUnsignedLong(Plugin& plugin, uint32_t value, NPVariant& variant) { QCC_UNUSED(plugin); DOUBLE_TO_NPVARIANT(value, variant); } int64_t ToLongLong(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; if (value.type == NPVariantType_String) { /* * Special processing for int64 to allow larger precision than JS allows by converting string * values directly to int64 instead of first to doubles. */ qcc::String s = NPVARIANT_TO_STRING(value).UTF8Length ? qcc::String(NPVARIANT_TO_STRING(value).UTF8Characters, NPVARIANT_TO_STRING(value).UTF8Length) : qcc::String(); const char* nptr = s.c_str(); char* endptr; int64_t x = strtoll(nptr, &endptr, 0); typeError = (endptr == nptr); return x; } else { return ToInteger(plugin, value, typeError); } } void ToLongLong(Plugin& plugin, int64_t value, NPVariant& variant) { /* * Special processing for int64 to allow larger precision than JS allows by converting int64 * values to strings instead of first to doubles. */ char val[32]; snprintf(val, 32, "%" PRIi64, value); ToDOMString(plugin, val, strlen(val), variant); } uint64_t ToUnsignedLongLong(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; if (value.type == NPVariantType_String) { /* * Special processing for uint64 to allow larger precision than JS allows by converting string * values directly to uint64 instead of first to doubles. */ qcc::String s = NPVARIANT_TO_STRING(value).UTF8Length ? qcc::String(NPVARIANT_TO_STRING(value).UTF8Characters, NPVARIANT_TO_STRING(value).UTF8Length) : qcc::String(); const char* nptr = s.c_str(); char* endptr; uint64_t x = strtoull(nptr, &endptr, 0); typeError = (endptr == nptr); return x; } else { return ToInteger(plugin, value, typeError); } } void ToUnsignedLongLong(Plugin& plugin, uint64_t value, NPVariant& variant) { /* * Special processing for uint64 to allow larger precision than JS allows by converting int64 * values to strings instead of first to doubles. */ char val[32]; snprintf(val, 32, "%" PRIu64, value); ToDOMString(plugin, val, strlen(val), variant); } double ToDouble(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; return ToNumber(plugin, value, typeError); } void ToDouble(Plugin& plugin, double value, NPVariant& variant) { QCC_UNUSED(plugin); DOUBLE_TO_NPVARIANT(value, variant); } qcc::String ToDOMString(Plugin& plugin, const NPVariant& value, bool& typeError, bool treatNullAsEmptyString, bool treatUndefinedAsEmptyString) { typeError = false; if (NPVARIANT_IS_VOID(value) && treatUndefinedAsEmptyString) { return qcc::String(); } if (NPVARIANT_IS_NULL(value) && treatNullAsEmptyString) { return qcc::String(); } return ToString(plugin, value, typeError); } void ToDOMString(Plugin& plugin, qcc::String value, NPVariant& variant, TreatEmptyStringAs treatEmptyStringAs) { QCC_UNUSED(plugin); if (value.empty()) { switch (treatEmptyStringAs) { case TreatEmptyStringAsNull: NULL_TO_NPVARIANT(variant); return; case TreatEmptyStringAsUndefined: VOID_TO_NPVARIANT(variant); return; default: break; } } char* val = reinterpret_cast(NPN_MemAlloc(value.size() + 1)); strncpy(val, value.c_str(), value.size() + 1); STRINGZ_TO_NPVARIANT(val, variant); } void ToDOMString(Plugin& plugin, const char* str, uint32_t len, NPVariant& variant, TreatEmptyStringAs treatEmptyStringAs) { QCC_UNUSED(plugin); if (!str || (0 == len)) { switch (treatEmptyStringAs) { case TreatEmptyStringAsNull: NULL_TO_NPVARIANT(variant); return; case TreatEmptyStringAsUndefined: VOID_TO_NPVARIANT(variant); return; default: break; } } char* val = reinterpret_cast(NPN_MemAlloc(len + 1)); strncpy(val, str, len + 1); STRINGZ_TO_NPVARIANT(val, variant); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/npapi/Plugin.h0000644000175000017500000001050212620747066021317 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _PLUGIN_H #define _PLUGIN_H #include "npn.h" #include #include #include #include #include class NativeObject; class ScriptableObject; /** * Per-instance plugin data (controlled via NPP_New and NPP_Destroy). */ class _Plugin { public: /** * Plugin handle. This will be 0 after the NPP_Destroy is called. */ NPP npp; /** * HostObject constructor params (an impl of T). * * The runtime calls Allocate of the host object with two params, this plugin and an NPClass. * So the only way to pass params to the HostObject constructor is via this plugin or NPClass. * Adding the params to NPClass would make it global across all instances of the plugin which * could lead to race conditions. Adding the params to this plugin makes it per-instance and * thread-safe. */ void* params; /** * Cache of allocated HostObjects, keyed off the impl object. * * This means that as long as the runtime has not called Deallocate of a HostObject, then * HostObject::GetInstance() will just retain cached object and return it. */ std::map hostObjects; /** * Cache of retained NPObjects, keyed off the NativeObject wrapper. * * This is necessary as Firefox will delete native *retained* objects after calling * NPP_Destroy. This at least gives me a chance to null out the pointers when the plugin is * destroyed and not reference freed memory. */ std::map nativeObjects; QStatus Initialize(); /** * Compare two values for equality using the native '===' operator. * * This exists so that two native objects can be compared for equality. The pointers cannot * be compared since that does not work in chrome, so add a native function to the plugin * element to do the comparison for us (which does work in all the browsers). */ bool StrictEquals(const NPVariant& a, const NPVariant& b) const; /** * Return the security origin of this plugin instance. * * @param[out] origin a string of the form "://:" */ QStatus Origin(qcc::String& origin); /** * The characters (minus the quotes) "$-_.+!*'(),;/?:@=&" may appear unencoded in a URL. * Depending on the filesystem, these may not work for filenames, so encode all of them. * * For the curious, the intersection of unencoded characters and Windows is "/:*?". On Linux, * it is "/". * * @param url the URL to encode as a filename * * @return the encoded URL */ qcc::String ToFilename(const qcc::String& url); qcc::String KeyStoreFileName() { return qcc::String(); } bool RaiseBusError(QStatus code, const char* message = NULL); bool RaiseTypeError(const char* message); /* * Used only by HostObject and BusErrorInterface. Real support for throwing Error objects is * missing from NPAPI. */ class Error { public: /* Error fields */ qcc::String name; qcc::String message; /* BusError fields */ QStatus code; Error() : code(ER_NONE) { } void Clear() { name.clear(); message.clear(); code = ER_NONE; } }; Error error; void CheckError(NPObject* npobj); _Plugin(NPP npp); _Plugin(); ~_Plugin(); private: Error _error; }; typedef qcc::ManagedObj<_Plugin> Plugin; #endif alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionOptsInterface.cc0000644000175000017500000000426312620747066023231 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionOptsInterface.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _SessionOptsInterface::constants; std::map& _SessionOptsInterface::Constants() { if (constants.empty()) { CONSTANT("TRAFFIC_MESSAGES", 0x01); CONSTANT("TRAFFIC_RAW_UNRELIABLE", 0x02); CONSTANT("TRAFFIC_RAW_RELIABLE", 0x04); CONSTANT("PROXIMITY_ANY", 0xFF); CONSTANT("PROXIMITY_PHYSICAL", 0x01); CONSTANT("PROXIMITY_NETWORK", 0x02); CONSTANT("TRANSPORT_NONE", 0x0000); CONSTANT("TRANSPORT_LOCAL", 0x0001); CONSTANT("TRANSPORT_TCP", 0x0004); CONSTANT("TRANSPORT_UDP", 0x0100); CONSTANT("TRANSPORT_EXPERIMENTAL", 0x8000); CONSTANT("TRANSPORT_IP", 0x0104); CONSTANT("TRANSPORT_ANY", 0x0105); // CONSTANT("TRANSPORT_WLAN", 0x0004); // CONSTANT("TRANSPORT_WWAN", 0x0008); // CONSTANT("TRANSPORT_LAN", 0x0010); // CONSTANT("TRANSPORT_PROXIMITY", 0x0040); } return constants; } _SessionOptsInterface::_SessionOptsInterface(Plugin& plugin) : ScriptableObject(plugin, Constants()) { QCC_DbgTrace(("%s", __FUNCTION__)); } _SessionOptsInterface::~_SessionOptsInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SocketFdInterface.cc0000644000175000017500000001266012620747066022442 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SocketFdInterface.h" #include "CallbackNative.h" #include "HttpListenerNative.h" #include "SocketFdHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" _SocketFdInterface::_SocketFdInterface(Plugin& plugin) : ScriptableObject(plugin), httpServer(plugin) { QCC_DbgTrace(("%s", __FUNCTION__)); OPERATION("createObjectURL", &_SocketFdInterface::createObjectURL); OPERATION("revokeObjectURL", &_SocketFdInterface::revokeObjectURL); } _SocketFdInterface::~_SocketFdInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _SocketFdInterface::Construct(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String fd; const char* nptr; char* endptr; qcc::SocketFd socketFd; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } fd = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } nptr = fd.c_str(); socketFd = strtoll(nptr, &endptr, 0); typeError = (endptr == nptr); if (typeError) { plugin->RaiseTypeError("argument 0 is not a socket descriptor"); goto exit; } if (qcc::INVALID_SOCKET_FD != socketFd) { status = qcc::SocketDup(socketFd, socketFd); if (ER_OK != status) { QCC_LogError(status, ("SocketDup failed")); goto exit; } } { SocketFdHost socketFdHost(plugin, socketFd); ToHostObject(plugin, socketFdHost, *result); } exit: if ((ER_OK == status) && !typeError) { return true; } else { if (ER_OK != status) { plugin->RaiseBusError(status); } return false; } } bool _SocketFdInterface::createObjectURL(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; SocketFdHost* socketFd = NULL; CallbackNative* callbackNative = NULL; HttpListenerNative* httpListener = NULL; qcc::String url; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } socketFd = ToHostObject(plugin, args[0], typeError); if (typeError || !socketFd) { plugin->RaiseTypeError("argument 0 is not a SocketFd"); goto exit; } if (argCount > 2) { httpListener = ToNativeObject(plugin, args[1], typeError); if (typeError || !httpListener) { plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } status = httpServer->CreateObjectUrl((*socketFd)->GetFd(), httpListener, url); if (ER_OK == status) { httpListener = NULL; /* httpServer now owns httpListener */ QCC_DbgTrace(("url=%s", url.c_str())); } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status, url); callbackNative = NULL; } delete callbackNative; delete httpListener; VOID_TO_NPVARIANT(*result); return !typeError; } bool _SocketFdInterface::revokeObjectURL(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; QStatus status = ER_OK; qcc::String url; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } url = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } QCC_DbgTrace(("url=%s", url.c_str())); httpServer->RevokeObjectUrl(url); exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionLostListenerNative.h0000644000175000017500000000241612620747066024121 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONLOSTLISTENERNATIVE_H #define _SESSIONLOSTLISTENERNATIVE_H #include "NativeObject.h" #include #include class SessionLostListenerNative : public NativeObject { public: SessionLostListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~SessionLostListenerNative(); void onLost(ajn::SessionId id, ajn::SessionListener::SessionLostReason reason); }; #endif // _SESSIONLOSTLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AcceptSessionJoinerListenerNative.cc0000644000175000017500000000410512620747066025701 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "AcceptSessionJoinerListenerNative.h" #include "SessionOptsHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" AcceptSessionJoinerListenerNative::AcceptSessionJoinerListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } AcceptSessionJoinerListenerNative::~AcceptSessionJoinerListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool AcceptSessionJoinerListenerNative::onAccept(ajn::SessionPort sessionPort, const qcc::String& joiner, SessionOptsHost& opts) { QCC_DbgTrace(("%s(sessionPort=%d,joiner=%s)", __FUNCTION__, sessionPort, joiner.c_str())); NPVariant npargs[3]; ToUnsignedShort(plugin, sessionPort, npargs[0]); ToDOMString(plugin, joiner, npargs[1]); ToHostObject(plugin, opts, npargs[2]); bool accepted = false; NPVariant result = NPVARIANT_VOID; if (NPN_InvokeDefault(plugin->npp, objectValue, npargs, 3, &result)) { bool ignore; /* Can convert any JS type into a boolean type. */ accepted = ToBoolean(plugin, result, ignore); } NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); NPN_ReleaseVariantValue(&npargs[1]); return accepted; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SocketFdHost.h0000644000175000017500000000303612620747066021316 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SOCKETFDHOST_H #define _SOCKETFDHOST_H #include "ScriptableObject.h" class _SocketFdHost : public ScriptableObject { public: _SocketFdHost(Plugin& plugin, qcc::SocketFd& socketFd); virtual ~_SocketFdHost(); qcc::SocketFd GetFd() { return socketFd; } private: qcc::SocketFd socketFd; bool getFd(NPVariant* result); bool close(const NPVariant* args, uint32_t argCount, NPVariant* result); bool shutdown(const NPVariant* args, uint32_t argCount, NPVariant* result); bool recv(const NPVariant* args, uint32_t argCount, NPVariant* result); bool send(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_SocketFdHost> SocketFdHost; #endif // _SOCKETFDHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/InterfaceDescriptionNative.cc0000644000175000017500000006657512620747066024410 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "InterfaceDescriptionNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" QStatus InterfaceDescriptionNative::CreateInterface(Plugin& plugin, BusAttachment& busAttachment, InterfaceDescriptionNative* interfaceDescriptionNative) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String name; bool typeError = false; ajn::InterfaceDescription* interface; ajn::InterfaceSecurityPolicy secPolicy; NPVariant length; NPVariant method; NPVariant signal; NPVariant property; NPVariant npSecPolicy; NPVariant npname; QStatus status = ER_OK; VOID_TO_NPVARIANT(npname); if (!NPN_GetProperty(plugin->npp, interfaceDescriptionNative->objectValue, NPN_GetStringIdentifier("name"), &npname)) { status = ER_FAIL; QCC_LogError(status, ("Failed to get 'name' property")); goto exit; } name = ToDOMString(plugin, npname, typeError); if (typeError) { goto exit; } VOID_TO_NPVARIANT(npSecPolicy); if (!NPN_GetProperty(plugin->npp, interfaceDescriptionNative->objectValue, NPN_GetStringIdentifier("secPolicy"), &npSecPolicy)) { QCC_LogError(ER_FAIL, ("Failed to get 'secPolicy' property, defaulting to INHERIT")); INT32_TO_NPVARIANT(ajn::AJ_IFC_SECURITY_INHERIT, npSecPolicy); } if (NPVARIANT_IS_VOID(npSecPolicy)) { NPVariant secure; bool sec = false; QCC_DbgPrintf(("'secPolicy' property not specified, check for deprecated 'secure' property.")); VOID_TO_NPVARIANT(secure); if (NPN_GetProperty(plugin->npp, interfaceDescriptionNative->objectValue, NPN_GetStringIdentifier("secure"), &secure)) { sec = ToBoolean(plugin, secure, typeError); assert(!typeError); /* ToBoolean should never fail */ if (typeError) { QCC_LogError(ER_FAIL, ("ToBoolean failed")); goto exit; } } else { QCC_DbgPrintf(("Failed to get 'secure' property, defaulting secPolicy to INHERIT")); } INT32_TO_NPVARIANT(sec ? ajn::AJ_IFC_SECURITY_REQUIRED : ajn::AJ_IFC_SECURITY_INHERIT, npSecPolicy); } secPolicy = static_cast(ToLong(plugin, npSecPolicy, typeError)); if (typeError) { QCC_LogError(ER_FAIL, ("ToLong failed")); goto exit; } status = busAttachment->CreateInterface(name.c_str(), interface, secPolicy); if (ER_OK != status) { goto exit; } typedef std::map AnnotationsMap; VOID_TO_NPVARIANT(method); VOID_TO_NPVARIANT(length); if (NPN_GetProperty(plugin->npp, interfaceDescriptionNative->objectValue, NPN_GetStringIdentifier("method"), &method) && NPVARIANT_IS_OBJECT(method) && NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetStringIdentifier("length"), &length) && (NPVARIANT_IS_INT32(length) || NPVARIANT_IS_DOUBLE(length))) { bool ignored; int32_t n = ToLong(plugin, length, ignored); for (int32_t i = 0; (ER_OK == status) && (i < n); ++i) { NPVariant element = NPVARIANT_VOID; if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetIntIdentifier(i), &element) && NPVARIANT_IS_OBJECT(element)) { qcc::String name, signature, returnSignature, argNames; AnnotationsMap annotations; NPIdentifier* properties = NULL; uint32_t propertiesCount = 0; if (NPN_Enumerate(plugin->npp, NPVARIANT_TO_OBJECT(element), &properties, &propertiesCount)) { for (uint32_t i = 0; (ER_OK == status) && (i < propertiesCount); ++i) { if (!NPN_IdentifierIsString(properties[i])) { continue; } NPUTF8* property = NPN_UTF8FromIdentifier(properties[i]); if (!property) { status = ER_OUT_OF_MEMORY; break; } NPVariant npvalue = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(element), properties[i], &npvalue)) { continue; } qcc::String value = ToDOMString(plugin, npvalue, typeError); if (typeError) { continue; } NPN_ReleaseVariantValue(&npvalue); if (!strcmp(property, "name")) { name = value; } else if (!strcmp(property, "signature")) { signature = value; } else if (!strcmp(property, "returnSignature")) { returnSignature = value; } else if (!strcmp(property, "argNames")) { argNames = value; } else { annotations[property] = value; } NPN_MemFree(property); } NPN_MemFree(properties); } status = interface->AddMember(ajn::MESSAGE_METHOD_CALL, name.empty() ? 0 : name.c_str(), signature.empty() ? 0 : signature.c_str(), returnSignature.empty() ? 0 : returnSignature.c_str(), argNames.empty() ? 0 : argNames.c_str()); for (AnnotationsMap::const_iterator it = annotations.begin(); it != annotations.end(); ++it) { interface->AddMemberAnnotation(name.c_str(), it->first, it->second); } } NPN_ReleaseVariantValue(&element); } } NPN_ReleaseVariantValue(&length); NPN_ReleaseVariantValue(&method); if (ER_OK != status) { goto exit; } VOID_TO_NPVARIANT(signal); VOID_TO_NPVARIANT(length); if (NPN_GetProperty(plugin->npp, interfaceDescriptionNative->objectValue, NPN_GetStringIdentifier("signal"), &signal) && NPVARIANT_IS_OBJECT(signal) && NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signal), NPN_GetStringIdentifier("length"), &length) && (NPVARIANT_IS_INT32(length) || NPVARIANT_IS_DOUBLE(length))) { bool ignored; int32_t n = ToLong(plugin, length, ignored); for (int32_t i = 0; (ER_OK == status) && (i < n); ++i) { NPVariant element = NPVARIANT_VOID; if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signal), NPN_GetIntIdentifier(i), &element) && NPVARIANT_IS_OBJECT(element)) { qcc::String name, signature, argNames; AnnotationsMap annotations; NPIdentifier* properties = NULL; uint32_t propertiesCount = 0; if (NPN_Enumerate(plugin->npp, NPVARIANT_TO_OBJECT(element), &properties, &propertiesCount)) { for (uint32_t i = 0; (ER_OK == status) && (i < propertiesCount); ++i) { if (!NPN_IdentifierIsString(properties[i])) { continue; } NPUTF8* property = NPN_UTF8FromIdentifier(properties[i]); if (!property) { status = ER_OUT_OF_MEMORY; break; } NPVariant npvalue = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(element), properties[i], &npvalue)) { continue; } qcc::String value = ToDOMString(plugin, npvalue, typeError); if (typeError) { continue; } NPN_ReleaseVariantValue(&npvalue); if (!strcmp(property, "name")) { name = value; } else if (!strcmp(property, "signature")) { signature = value; } else if (!strcmp(property, "argNames")) { argNames = value; } else { annotations[property] = value; } NPN_MemFree(property); } NPN_MemFree(properties); } status = interface->AddMember(ajn::MESSAGE_SIGNAL, name.empty() ? 0 : name.c_str(), signature.empty() ? 0 : signature.c_str(), NULL, argNames.empty() ? 0 : argNames.c_str()); for (AnnotationsMap::const_iterator it = annotations.begin(); it != annotations.end(); ++it) { interface->AddMemberAnnotation(name.c_str(), it->first, it->second); } } NPN_ReleaseVariantValue(&element); } } NPN_ReleaseVariantValue(&length); NPN_ReleaseVariantValue(&signal); if (ER_OK != status) { goto exit; } VOID_TO_NPVARIANT(property); VOID_TO_NPVARIANT(length); if (NPN_GetProperty(plugin->npp, interfaceDescriptionNative->objectValue, NPN_GetStringIdentifier("property"), &property) && NPVARIANT_IS_OBJECT(property) && NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(property), NPN_GetStringIdentifier("length"), &length) && (NPVARIANT_IS_INT32(length) || NPVARIANT_IS_DOUBLE(length))) { bool ignored; int32_t n = ToLong(plugin, length, ignored); for (int32_t i = 0; (ER_OK == status) && (i < n); ++i) { NPVariant element = NPVARIANT_VOID; if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(property), NPN_GetIntIdentifier(i), &element) && NPVARIANT_IS_OBJECT(element)) { qcc::String name, signature; uint8_t accessFlags = 0; AnnotationsMap annotations; NPIdentifier* properties = NULL; uint32_t propertiesCount = 0; if (NPN_Enumerate(plugin->npp, NPVARIANT_TO_OBJECT(element), &properties, &propertiesCount)) { for (uint32_t i = 0; (ER_OK == status) && (i < propertiesCount); ++i) { if (!NPN_IdentifierIsString(properties[i])) { continue; } NPUTF8* property = NPN_UTF8FromIdentifier(properties[i]); if (!property) { status = ER_OUT_OF_MEMORY; break; } NPVariant npvalue = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(element), properties[i], &npvalue)) { continue; } qcc::String value = ToDOMString(plugin, npvalue, typeError); if (typeError) { continue; } NPN_ReleaseVariantValue(&npvalue); if (!strcmp(property, "name")) { name = value; } else if (!strcmp(property, "signature")) { signature = value; } else if (!strcmp(property, "access")) { if (value == "readwrite") { accessFlags = ajn::PROP_ACCESS_RW; } else if (value == "read") { accessFlags = ajn::PROP_ACCESS_READ; } else if (value == "write") { accessFlags = ajn::PROP_ACCESS_WRITE; } } else { annotations[property] = value; } NPN_MemFree(property); } NPN_MemFree(properties); } status = interface->AddProperty(name.empty() ? 0 : name.c_str(), signature.empty() ? 0 : signature.c_str(), accessFlags); for (AnnotationsMap::const_iterator it = annotations.begin(); (ER_OK == status) && (it != annotations.end()); ++it) { status = interface->AddPropertyAnnotation(name, it->first, it->second); } } NPN_ReleaseVariantValue(&element); } } NPN_ReleaseVariantValue(&length); NPN_ReleaseVariantValue(&property); if (ER_OK != status) { goto exit; } interface->Activate(); #if !defined(NDEBUG) { qcc::String str = interface->Introspect(); QCC_DbgTrace(("%s", str.c_str())); } #endif exit: if (typeError) { return ER_FAIL; } else { return status; } } InterfaceDescriptionNative* InterfaceDescriptionNative::GetInterface(Plugin& plugin, BusAttachment& busAttachment, const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); NPVariant npname = NPVARIANT_VOID; NPVariant value = NPVARIANT_VOID; size_t numMembers = 0; const ajn::InterfaceDescription::Member** members = NULL; size_t numMethods = 0; size_t numSignals = 0; size_t numProps = 0; NPVariant methodArray = NPVARIANT_VOID; NPVariant method = NPVARIANT_VOID; NPVariant secPolicy = NPVARIANT_VOID; NPVariant signalArray = NPVARIANT_VOID; NPVariant signal = NPVARIANT_VOID; const ajn::InterfaceDescription::Property** props = NULL; NPVariant propertyArray = NPVARIANT_VOID; NPVariant property = NPVARIANT_VOID; QStatus status = ER_OK; InterfaceDescriptionNative* interfaceDescriptionNative = NULL; bool typeError = false; const ajn::InterfaceDescription* iface = busAttachment->GetInterface(name.c_str()); if (iface) { if (!NewObject(plugin, value)) { status = ER_FAIL; QCC_LogError(status, ("NewObject failed")); goto exit; } ToDOMString(plugin, name, npname); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("name"), &npname)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } NPN_ReleaseVariantValue(&npname); VOID_TO_NPVARIANT(npname); if (iface->GetSecurityPolicy() != ajn::AJ_IFC_SECURITY_INHERIT) { INT32_TO_NPVARIANT(iface->GetSecurityPolicy(), secPolicy); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("secPolicy"), &secPolicy)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } numMembers = iface->GetMembers(); members = new const ajn::InterfaceDescription::Member*[numMembers]; iface->GetMembers(members, numMembers); for (size_t i = 0; i < numMembers; ++i) { switch (members[i]->memberType) { case ajn::MESSAGE_METHOD_CALL: ++numMethods; break; case ajn::MESSAGE_SIGNAL: ++numSignals; break; default: break; } } numProps = iface->GetProperties(); if (numMethods) { if (!NewArray(plugin, methodArray)) { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); goto exit; } for (size_t i = 0, j = 0; i < numMembers; ++i) { if (ajn::MESSAGE_METHOD_CALL == members[i]->memberType) { if (!NewObject(plugin, method)) { status = ER_FAIL; QCC_LogError(status, ("NewObject failed")); goto exit; } NPVariant name, signature, returnSignature, argNames; STRINGZ_TO_NPVARIANT(members[i]->name.c_str(), name); STRINGZ_TO_NPVARIANT(members[i]->signature.c_str(), signature); STRINGZ_TO_NPVARIANT(members[i]->returnSignature.c_str(), returnSignature); STRINGZ_TO_NPVARIANT(members[i]->argNames.c_str(), argNames); bool set = NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetStringIdentifier("name"), &name) && NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetStringIdentifier("signature"), &signature) && NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetStringIdentifier("returnSignature"), &returnSignature) && NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetStringIdentifier("argNames"), &argNames); if (!set) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } const size_t numAnnotations = members[i]->GetAnnotations(); qcc::String* names = new qcc::String[numAnnotations]; qcc::String* values = new qcc::String[numAnnotations]; members[i]->GetAnnotations(names, values, numAnnotations); for (size_t ann = 0; ann < numAnnotations; ++ann) { NPVariant annotation; STRINGZ_TO_NPVARIANT(values[ann].c_str(), annotation); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(method), NPN_GetStringIdentifier(names[ann].c_str()), &annotation)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } delete [] names; delete [] values; if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(methodArray), NPN_GetIntIdentifier(j++), &method)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } NPN_ReleaseVariantValue(&method); VOID_TO_NPVARIANT(method); } } if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("method"), &methodArray)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } if (numSignals) { if (!NewArray(plugin, signalArray)) { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); goto exit; } for (size_t i = 0, j = 0; i < numMembers; ++i) { if (ajn::MESSAGE_SIGNAL == members[i]->memberType) { if (!NewObject(plugin, signal)) { status = ER_FAIL; QCC_LogError(status, ("NewObject failed")); goto exit; } NPVariant name, signature, argNames; STRINGZ_TO_NPVARIANT(members[i]->name.c_str(), name); STRINGZ_TO_NPVARIANT(members[i]->signature.c_str(), signature); STRINGZ_TO_NPVARIANT(members[i]->argNames.c_str(), argNames); bool set = NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signal), NPN_GetStringIdentifier("name"), &name) && NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signal), NPN_GetStringIdentifier("signature"), &signature) && NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signal), NPN_GetStringIdentifier("argNames"), &argNames); if (!set) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } const size_t numAnnotations = members[i]->GetAnnotations(); qcc::String* names = new qcc::String[numAnnotations]; qcc::String* values = new qcc::String[numAnnotations]; members[i]->GetAnnotations(names, values, numAnnotations); for (size_t ann = 0; ann < numAnnotations; ++ann) { NPVariant annotation; STRINGZ_TO_NPVARIANT(values[ann].c_str(), annotation); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signal), NPN_GetStringIdentifier(names[ann].c_str()), &annotation)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } delete [] names; delete [] values; if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(signalArray), NPN_GetIntIdentifier(j++), &signal)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } NPN_ReleaseVariantValue(&signal); VOID_TO_NPVARIANT(signal); } if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("signal"), &signalArray)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } if (numProps) { props = new const ajn::InterfaceDescription::Property*[numProps]; iface->GetProperties(props, numProps); if (!NewArray(plugin, propertyArray)) { status = ER_FAIL; QCC_LogError(status, ("NewArray failed")); goto exit; } for (size_t i = 0, j = 0; i < numProps; ++i) { if (!NewObject(plugin, property)) { status = ER_FAIL; QCC_LogError(status, ("NewObject failed")); goto exit; } NPVariant name, signature; STRINGZ_TO_NPVARIANT(props[i]->name.c_str(), name); STRINGZ_TO_NPVARIANT(props[i]->signature.c_str(), signature); bool set = NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(property), NPN_GetStringIdentifier("name"), &name) && NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(property), NPN_GetStringIdentifier("signature"), &signature); if (!set) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } NPVariant access; if (props[i]->access == ajn::PROP_ACCESS_RW) { STRINGZ_TO_NPVARIANT("readwrite", access); } else if (props[i]->access == ajn::PROP_ACCESS_READ) { STRINGZ_TO_NPVARIANT("read", access); } else if (props[i]->access == ajn::PROP_ACCESS_WRITE) { STRINGZ_TO_NPVARIANT("write", access); } if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(property), NPN_GetStringIdentifier("access"), &access)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } const size_t numAnnotations = props[i]->GetAnnotations(); qcc::String* names = new qcc::String[numAnnotations]; qcc::String* values = new qcc::String[numAnnotations]; props[i]->GetAnnotations(names, values, numAnnotations); for (size_t ann = 0; ann < numAnnotations; ++ann) { NPVariant annotation; STRINGZ_TO_NPVARIANT(values[ann].c_str(), annotation); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(property), NPN_GetStringIdentifier(names[ann].c_str()), &annotation)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } delete [] names; delete [] values; if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(propertyArray), NPN_GetIntIdentifier(j++), &property)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } NPN_ReleaseVariantValue(&property); VOID_TO_NPVARIANT(property); } if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(value), NPN_GetStringIdentifier("property"), &propertyArray)) { status = ER_FAIL; QCC_LogError(status, ("NPN_SetProperty failed")); goto exit; } } interfaceDescriptionNative = ToNativeObject(plugin, value, typeError); if (typeError || !interfaceDescriptionNative) { typeError = true; goto exit; } } exit: NPN_ReleaseVariantValue(&property); NPN_ReleaseVariantValue(&propertyArray); delete[] props; NPN_ReleaseVariantValue(&signal); NPN_ReleaseVariantValue(&signalArray); NPN_ReleaseVariantValue(&method); NPN_ReleaseVariantValue(&methodArray); delete[] members; NPN_ReleaseVariantValue(&value); return interfaceDescriptionNative; } InterfaceDescriptionNative::InterfaceDescriptionNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } InterfaceDescriptionNative::InterfaceDescriptionNative(InterfaceDescriptionNative* other) : NativeObject(other->plugin, other->objectValue) { } InterfaceDescriptionNative::~InterfaceDescriptionNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionLostReasonInterface.cc0000644000175000017500000000365012620747066024374 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionLostReasonInterface.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _SessionLostReasonInterface::constants; std::map& _SessionLostReasonInterface::Constants() { if (constants.empty()) { CONSTANT("INVALID", 0x00); /**< Invalid */ CONSTANT("REMOTE_END_LEFT_SESSION", 0x01); /**< Remote end called LeaveSession */ CONSTANT("REMOTE_END_CLOSED_ABRUPTLY", 0x02); /**< Remote end closed abruptly */ CONSTANT("REMOVED_BY_BINDER", 0x03); /**< Session binder removed this endpoint by calling RemoveSessionMember */ CONSTANT("LINK_TIMEOUT", 0x04); /**< Link was timed-out */ CONSTANT("REASON_OTHER", 0x05); /**< Unspecified reason for session loss */ } return constants; } _SessionLostReasonInterface::_SessionLostReasonInterface(Plugin& plugin) : ScriptableObject(plugin, Constants()) { QCC_DbgTrace(("%s", __FUNCTION__)); } _SessionLostReasonInterface::~_SessionLostReasonInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionMemberRemovedListenerNative.cc0000644000175000017500000000327612620747066026074 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionMemberRemovedListenerNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" SessionMemberRemovedListenerNative::SessionMemberRemovedListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } SessionMemberRemovedListenerNative::~SessionMemberRemovedListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void SessionMemberRemovedListenerNative::onMemberRemoved(ajn::SessionId id, const qcc::String& uniqueName) { QCC_DbgTrace(("%s(id=%u,uniqueName=%s)", __FUNCTION__, id, uniqueName.c_str())); NPVariant npargs[2]; ToUnsignedLong(plugin, id, npargs[0]); ToDOMString(plugin, uniqueName, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AuthListenerNative.h0000644000175000017500000000316312620747066022535 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _AUTHLISTENERNATIVE_H #define _AUTHLISTENERNATIVE_H #include "CredentialsHost.h" #include "MessageHost.h" #include "NativeObject.h" #include #include class AuthListenerNative : public NativeObject { public: AuthListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~AuthListenerNative(); bool onRequest(qcc::String& authMechanism, qcc::String& peerName, uint16_t authCount, qcc::String& userName, uint16_t credMask, CredentialsHost& credentials); bool onVerify(qcc::String& authMechanism, qcc::String& peerName, CredentialsHost& credentials); void onSecurityViolation(QStatus status, MessageHost& message); void onComplete(qcc::String& authMechanism, qcc::String& peerName, bool success); }; #endif // _AUTHLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/CredentialsInterface.h0000644000175000017500000000245112620747066023034 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _CREDENTIALSINTERFACE_H #define _CREDENTIALSINTERFACE_H #include "ScriptableObject.h" #include class _CredentialsInterface : public ScriptableObject { public: static std::map& Constants(); _CredentialsInterface(Plugin& plugin); virtual ~_CredentialsInterface(); private: static std::map constants; }; typedef qcc::ManagedObj<_CredentialsInterface> CredentialsInterface; #endif // _CREDENTIALSINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageListenerNative.cc0000644000175000017500000000440712620747066023360 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "MessageListenerNative.h" #include "MessageHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" MessageListenerNative::MessageListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } MessageListenerNative::~MessageListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void MessageListenerNative::onMessage(MessageHost& message, const ajn::MsgArg* args, size_t numArgs) { QCC_DbgTrace(("%s(args=%p,numArgs=%d)", __FUNCTION__, args, numArgs)); #if !defined(NDEBUG) qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); #endif QStatus status = ER_OK; uint32_t npargCount = 1 + numArgs; NPVariant* npargs = new NPVariant[npargCount]; ToHostObject(plugin, message, npargs[0]); size_t i; for (i = 0; (ER_OK == status) && (i < numArgs); ++i) { ToAny(plugin, args[i], npargs[1 + i], status); } NPVariant result = NPVARIANT_VOID; if (ER_OK == status) { if (!NPN_InvokeDefault(plugin->npp, objectValue, npargs, npargCount, &result)) { status = ER_FAIL; QCC_LogError(status, ("NPN_InvokeDefault failed")); } } else { npargCount = 1 + i; } for (uint32_t j = 0; j < npargCount; ++j) { NPN_ReleaseVariantValue(&npargs[j]); } delete[] npargs; NPN_ReleaseVariantValue(&result); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SuccessListenerNative.h0000644000175000017500000000216712620747066023247 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SUCCESSLISTENERNATIVE_H #define _SUCCESSLISTENERNATIVE_H #include "NativeObject.h" class SuccessListenerNative : public NativeObject { public: SuccessListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~SuccessListenerNative(); void onSuccess(); }; #endif // _SUCCESSLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HttpRequestHost.cc0000644000175000017500000001160212620747066022240 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "HttpRequestHost.h" #include "TypeMapping.h" #include #include #define QCC_MODULE "ALLJOYN_JS" _HttpRequestHost::_HttpRequestHost(Plugin& plugin, HttpServer& httpServer, Http::Headers& requestHeaders, qcc::SocketStream& stream, qcc::SocketFd sessionFd) : ScriptableObject(plugin), httpServer(httpServer), requestHeaders(requestHeaders), stream(stream), sessionFd(sessionFd) { QCC_DbgTrace(("%s", __FUNCTION__)); /* Default response */ status = 200; statusText = "OK"; responseHeaders["Date"] = qcc::UTCTime(); responseHeaders["Content-Type"] = "application/octet-stream"; ATTRIBUTE("status", &_HttpRequestHost::getStatus, &_HttpRequestHost::setStatus); ATTRIBUTE("statusText", &_HttpRequestHost::getStatusText, &_HttpRequestHost::setStatusText); OPERATION("getAllRequestHeaders", &_HttpRequestHost::getAllRequestHeaders); OPERATION("getRequestHeader", &_HttpRequestHost::getRequestHeader); OPERATION("setResponseHeader", &_HttpRequestHost::setResponseHeader); OPERATION("send", &_HttpRequestHost::send); } _HttpRequestHost::~_HttpRequestHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _HttpRequestHost::getStatus(NPVariant* result) { ToUnsignedShort(plugin, status, *result); return true; } bool _HttpRequestHost::setStatus(const NPVariant* value) { bool typeError = false; status = ToUnsignedShort(plugin, *value, typeError); return !typeError; } bool _HttpRequestHost::getStatusText(NPVariant* result) { ToDOMString(plugin, statusText, *result); return true; } bool _HttpRequestHost::setStatusText(const NPVariant* value) { bool typeError = false; statusText = ToDOMString(plugin, *value, typeError); return !typeError; } bool _HttpRequestHost::getAllRequestHeaders(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String headers; for (Http::Headers::iterator it = requestHeaders.begin(); it != requestHeaders.end(); ++it) { headers += it->first + ": " + it->second + "\r\n"; } ToDOMString(plugin, headers, *result); return true; } bool _HttpRequestHost::getRequestHeader(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String header; qcc::String value; Http::Headers::iterator it; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } header = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } it = requestHeaders.find(header); // TODO should be case-insensitive if (it != requestHeaders.end()) { value = it->second; } exit: ToDOMString(plugin, value, *result, TreatEmptyStringAsNull); return !typeError; } bool _HttpRequestHost::setResponseHeader(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String header; qcc::String value; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } header = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } value = ToDOMString(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } QCC_DbgTrace(("%s: %s", header.c_str(), value.c_str())); responseHeaders[header] = value; exit: VOID_TO_NPVARIANT(*result); return !typeError; } bool _HttpRequestHost::send(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_UNUSED(result); QCC_DbgTrace(("%s", __FUNCTION__)); httpServer->SendResponse(stream, status, statusText, responseHeaders, sessionFd); return true; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageHost.cc0000644000175000017500000000673712620747066021351 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "MessageHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" _MessageHost::_MessageHost(Plugin& plugin, BusAttachment& busAttachment, ajn::Message& message) : ScriptableObject(plugin, _MessageInterface::Constants()), busAttachment(busAttachment), message(message) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("sender", &_MessageHost::getSender, 0); ATTRIBUTE("destination", &_MessageHost::getDestination, 0); ATTRIBUTE("flags", &_MessageHost::getFlags, 0); ATTRIBUTE("interfaceName", &_MessageHost::getInterfaceName, 0); ATTRIBUTE("objectPath", &_MessageHost::getObjectPath, 0); ATTRIBUTE("authMechanism", &_MessageHost::getAuthMechanism, 0); ATTRIBUTE("isUnreliable", &_MessageHost::getIsUnreliable, 0); ATTRIBUTE("memberName", &_MessageHost::getMemberName, 0); ATTRIBUTE("signature", &_MessageHost::getSignature, 0); ATTRIBUTE("sessionId", &_MessageHost::getSessionId, 0); } _MessageHost::~_MessageHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _MessageHost::getSender(NPVariant* result) { ToDOMString(plugin, message->GetSender(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getDestination(NPVariant* result) { ToDOMString(plugin, message->GetDestination(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getFlags(NPVariant* result) { ToUnsignedLong(plugin, message->GetFlags(), *result); return true; } bool _MessageHost::getInterfaceName(NPVariant* result) { ToDOMString(plugin, message->GetInterface(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getObjectPath(NPVariant* result) { ToDOMString(plugin, message->GetObjectPath(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getAuthMechanism(NPVariant* result) { ToDOMString(plugin, message->GetAuthMechanism(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getIsUnreliable(NPVariant* result) { ToBoolean(plugin, message->IsUnreliable(), *result); return true; } bool _MessageHost::getMemberName(NPVariant* result) { ToDOMString(plugin, message->GetMemberName(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getSignature(NPVariant* result) { ToDOMString(plugin, message->GetSignature(), *result, TreatEmptyStringAsUndefined); return true; } bool _MessageHost::getSessionId(NPVariant* result) { ToUnsignedLong(plugin, message->GetSessionId(), *result); return true; } bool _MessageHost::getTimestamp(NPVariant* result) { ToUnsignedLong(plugin, message->GetTimeStamp(), *result); return true; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusObjectNative.h0000644000175000017500000000331112620747066022001 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSOBJECTNATIVE_H #define _BUSOBJECTNATIVE_H #include "MessageReplyHost.h" #include "NativeObject.h" #include #include #include class BusObjectNative : public NativeObject { public: BusObjectNative(Plugin& plugin, NPObject* objectValue); virtual ~BusObjectNative(); void onRegistered(); void onUnregistered(); QStatus get(const ajn::InterfaceDescription* interface, const ajn::InterfaceDescription::Property* property, ajn::MsgArg& val); QStatus set(const ajn::InterfaceDescription* interface, const ajn::InterfaceDescription::Property* property, const ajn::MsgArg& val); QStatus toXML(bool deep, size_t indent, qcc::String& xml); void onMessage(const char* interfaceName, const char* methodName, MessageReplyHost& message, const ajn::MsgArg* args, size_t numArgs); }; #endif // _BUSOBJECTNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusErrorHost.h0000644000175000017500000000300012620747066021346 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSERRORHOST_H #define _BUSERRORHOST_H #include "ScriptableObject.h" #include #include #include class _BusErrorHost : public ScriptableObject { public: _BusErrorHost(Plugin& plugin, const qcc::String& name, const qcc::String& message, QStatus code); _BusErrorHost(Plugin& plugin, QStatus code); virtual ~_BusErrorHost(); qcc::String ToString(); private: const qcc::String name; const qcc::String message; QStatus code; bool getName(NPVariant* result); bool getMessage(NPVariant* result); bool getCode(NPVariant* result); }; typedef qcc::ManagedObj<_BusErrorHost> BusErrorHost; #endif // _BUSERRORHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusAttachment.h0000644000175000017500000000177712620747066021532 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSATTACHMENT_H #define _BUSATTACHMENT_H #include #include typedef qcc::ManagedObj BusAttachment; #endif // _BUSATTACHMENT_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/VersionInterface.h0000644000175000017500000000274712620747066022234 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _VERSIONINTERFACE_H #define _VERSIONINTERFACE_H #include "ScriptableObject.h" #include class _VersionInterface : public ScriptableObject { public: _VersionInterface(Plugin& plugin); virtual ~_VersionInterface(); private: bool getBuildInfo(NPVariant* result); bool getNumericVersion(NPVariant* result); bool getArch(NPVariant* result); bool getApiLevel(NPVariant* result); bool getRelease(NPVariant* result); bool getVersion(NPVariant* result); //bool toString(const NPVariant* args, uint32_t npargCount, NPVariant* result); }; typedef qcc::ManagedObj<_VersionInterface> VersionInterface; #endif // _VERSIONINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AcceptSessionJoinerListenerNative.h0000644000175000017500000000247212620747066025550 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _ACCEPTSESSIONJOINERLISTENERNATIVE_H #define _ACCEPTSESSIONJOINERLISTENERNATIVE_H #include "NativeObject.h" #include "SessionOptsHost.h" #include class AcceptSessionJoinerListenerNative : public NativeObject { public: AcceptSessionJoinerListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~AcceptSessionJoinerListenerNative(); bool onAccept(ajn::SessionPort port, const qcc::String& joiner, SessionOptsHost& opts); }; #endif // _ACCEPTSESSIONJOINERLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/ProxyBusObject.h0000644000175000017500000000200512620747066021673 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _PROXYBUSOBJECT_H #define _PROXYBUSOBJECT_H #include #include typedef qcc::ManagedObj ProxyBusObject; #endif // _PROXYBUSOBJECT_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/IfcSecurityInterface.cc0000644000175000017500000000315012620747066023163 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "IfcSecurityInterface.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _IfcSecurityInterface::constants; std::map& _IfcSecurityInterface::Constants() { if (constants.empty()) { CONSTANT("INHERIT", 0x00); /**< Inherit the security of the object that implements the interface */ CONSTANT("REQUIRED", 0x01); /**< Security is required for an interface */ CONSTANT("OFF", 0x02); /**< Security does not apply to this interface */ } return constants; } _IfcSecurityInterface::_IfcSecurityInterface(Plugin& plugin) : ScriptableObject(plugin, Constants()) { QCC_DbgTrace(("%s", __FUNCTION__)); } _IfcSecurityInterface::~_IfcSecurityInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageReplyHost.cc0000644000175000017500000001474712620747066022365 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "MessageReplyHost.h" #include "CallbackNative.h" #include "SignatureUtils.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" _MessageReplyHost::_MessageReplyHost(Plugin& plugin, BusAttachment& busAttachment, BusObject& busObject, ajn::Message& message, qcc::String replySignature) : _MessageHost(plugin, busAttachment, message), busObject(busObject), replySignature(replySignature) { QCC_DbgTrace(("%s(replySignature=%s)", __FUNCTION__, replySignature.c_str())); OPERATION("reply", &_MessageReplyHost::reply); OPERATION("replyError", &_MessageReplyHost::replyError); } _MessageReplyHost::~_MessageReplyHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _MessageReplyHost::reply(const NPVariant* npargs, uint32_t npargCount, NPVariant* npresult) { QCC_DbgTrace(("%s", __FUNCTION__)); size_t numArgs; const char* begin; ajn::MsgArg* args = NULL; CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; numArgs = ajn::SignatureUtils::CountCompleteTypes(replySignature.c_str()); if (npargCount < numArgs) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } args = new ajn::MsgArg[numArgs]; begin = replySignature.c_str(); for (size_t i = 0; i < numArgs; ++i) { const char* end = begin; status = ajn::SignatureUtils::ParseCompleteType(end); if (ER_OK != status) { goto exit; } qcc::String typeSignature(begin, end - begin); ToAny(plugin, npargs[i], typeSignature, args[i], typeError); if (typeError) { char message[128]; snprintf(message, sizeof(message), "argument %lu is not a '%s'", (unsigned long)i, typeSignature.c_str()); plugin->RaiseTypeError(message); goto exit; } begin = end; } if (npargCount > numArgs) { callbackNative = ToNativeObject(plugin, npargs[npargCount - 1], typeError); if (typeError) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } } #if !defined(NDEBUG) { qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); } #endif status = busObject->MethodReply(message, args, numArgs); exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; delete[] args; VOID_TO_NPVARIANT(*npresult); return !typeError; } /* * There several possible replyError method calls * - replyError( ) : status error * - replyError( , ) : status error with callback * - replyError( ) : error name * - replyError( , ) : error name and message * - replyError( , ) : error name and callback * - replyError( , , ) : error name, message, and callback */ bool _MessageReplyHost::replyError(const NPVariant* npargs, uint32_t npargCount, NPVariant* npresult) { QCC_DbgTrace(("%s, npargCount : %d", __FUNCTION__, npargCount)); CallbackNative* callbackNative = NULL; QStatus status = ER_OK; bool typeError = false; if (npargCount == 1 && NPVARIANT_IS_STRING(npargs[0])) { qcc::String errorName = ToDOMString(plugin, npargs[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } status = busObject->MethodReply(message, errorName.c_str(), 0); } else if (npargCount == 2 && (NPVARIANT_IS_INT32(npargs[0]) || NPVARIANT_IS_DOUBLE(npargs[0]))) { unsigned short code = ToUnsignedShort(plugin, npargs[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a number"); goto exit; } status = busObject->MethodReply(message, static_cast(code)); callbackNative = ToNativeObject(plugin, npargs[npargCount - 1], typeError); if (typeError) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } } else if (npargCount > 1 && NPVARIANT_IS_STRING(npargs[0])) { qcc::String errorName = ToDOMString(plugin, npargs[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } qcc::String errorMessage; if (npargCount > 1 && NPVARIANT_IS_STRING(npargs[1])) { errorMessage = ToDOMString(plugin, npargs[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } } status = busObject->MethodReply(message, errorName.c_str(), (npargCount > 1) ? errorMessage.c_str() : 0); if (npargCount > 1 && NPVARIANT_IS_OBJECT(npargs[npargCount - 1])) { callbackNative = ToNativeObject(plugin, npargs[npargCount - 1], typeError); if (typeError) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } } } else { typeError = true; plugin->RaiseTypeError("incorrect argument types"); goto exit; } exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; VOID_TO_NPVARIANT(*npresult); return !typeError; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SignalEmitterHost.cc0000644000175000017500000001500612620747066022521 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SignalEmitterHost.h" #include "CallbackNative.h" #include "SignatureUtils.h" #include "TypeMapping.h" #include #include #define QCC_MODULE "ALLJOYN_JS" _SignalEmitterHost::_SignalEmitterHost(Plugin& plugin, BusObject& busObject) : ScriptableObject(plugin), busObject(busObject) { QCC_DbgTrace(("%s", __FUNCTION__)); CALLER(&_SignalEmitterHost::emitSignal); } _SignalEmitterHost::~_SignalEmitterHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _SignalEmitterHost::emitSignal(const NPVariant* npargs, uint32_t npargCount, NPVariant* npresult) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String interfaceName; qcc::String signalName; CallbackNative* callbackNative = NULL; const ajn::InterfaceDescription* iface = NULL; const ajn::InterfaceDescription::Member* signal = NULL; size_t numArgs; const char* begin; ajn::MsgArg* args = NULL; ajn::SessionId sessionId = 0; qcc::String destination; uint16_t timeToLive = 0; uint8_t flags = 0; QStatus status = ER_OK; bool typeError = false; if (npargCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } interfaceName = ToDOMString(plugin, npargs[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } signalName = ToDOMString(plugin, npargs[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, npargs[npargCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } QCC_DbgTrace(("interfaceName=%s,signalName=%s", interfaceName.c_str(), signalName.c_str())); iface = busObject->busAttachment->GetInterface(interfaceName.c_str()); if (!iface) { status = ER_BUS_NO_SUCH_INTERFACE; goto exit; } signal = iface->GetMember(signalName.c_str()); if (!signal) { status = ER_BUS_INTERFACE_NO_SUCH_MEMBER; goto exit; } numArgs = ajn::SignatureUtils::CountCompleteTypes(signal->signature.c_str()); if ((npargCount - 3) < numArgs) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } args = new ajn::MsgArg[numArgs]; begin = signal->signature.c_str(); for (size_t i = 0; i < numArgs; ++i) { const char* end = begin; status = ajn::SignatureUtils::ParseCompleteType(end); if (ER_OK != status) { goto exit; } qcc::String typeSignature(begin, end - begin); ToAny(plugin, npargs[i + 2], typeSignature, args[i], typeError); if (typeError) { char message[128]; snprintf(message, sizeof(message), "argument %lu is not a '%s'", (unsigned long)i, typeSignature.c_str()); plugin->RaiseTypeError(message); goto exit; } begin = end; } if (numArgs < (npargCount - 3)) { NPVariant params = npargs[npargCount - 2]; if (!NPVARIANT_IS_OBJECT(params)) { typeError = true; char message[128]; snprintf(message, sizeof(message), "argument %d is not an object", npargCount - 2); plugin->RaiseTypeError(message); goto exit; } NPVariant value; VOID_TO_NPVARIANT(value); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(params), NPN_GetStringIdentifier("sessionId"), &value); if (!NPVARIANT_IS_VOID(value)) { sessionId = ToUnsignedLong(plugin, value, typeError); } NPN_ReleaseVariantValue(&value); if (typeError) { plugin->RaiseTypeError("'sessionId' is not a number"); goto exit; } VOID_TO_NPVARIANT(value); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(params), NPN_GetStringIdentifier("destination"), &value); if (!NPVARIANT_IS_VOID(value)) { destination = ToDOMString(plugin, value, typeError); } NPN_ReleaseVariantValue(&value); if (typeError) { plugin->RaiseTypeError("'destination' is not a string"); goto exit; } VOID_TO_NPVARIANT(value); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(params), NPN_GetStringIdentifier("timeToLive"), &value); if (!NPVARIANT_IS_VOID(value)) { timeToLive = ToUnsignedShort(plugin, value, typeError); } NPN_ReleaseVariantValue(&value); if (typeError) { plugin->RaiseTypeError("'timeToLive' is not a number"); goto exit; } VOID_TO_NPVARIANT(value); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(params), NPN_GetStringIdentifier("flags"), &value); if (!NPVARIANT_IS_VOID(value)) { flags = ToOctet(plugin, value, typeError); } NPN_ReleaseVariantValue(&value); if (typeError) { plugin->RaiseTypeError("'flags' is not a number"); goto exit; } } #if !defined(NDEBUG) { qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); } #endif status = busObject->Signal(destination.empty() ? 0 : destination.c_str(), sessionId, *signal, args, numArgs, timeToLive, flags); exit: if (!typeError && callbackNative) { CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; } delete callbackNative; delete[] args; VOID_TO_NPVARIANT(*npresult); return !typeError; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/IfcSecurityInterface.h0000644000175000017500000000245112620747066023030 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _IFCSECURITYINTERFACE_H #define _IFCSECURITYINTERFACE_H #include "ScriptableObject.h" #include class _IfcSecurityInterface : public ScriptableObject { public: static std::map& Constants(); _IfcSecurityInterface(Plugin& plugin); virtual ~_IfcSecurityInterface(); private: static std::map constants; }; typedef qcc::ManagedObj<_IfcSecurityInterface> IfcSecurityInterface; #endif // _IFCSECURITYINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusNamespace.h0000644000175000017500000000527512620747066021333 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSNAMESPACE_H #define _BUSNAMESPACE_H #include "BusAttachmentInterface.h" #include "BusErrorInterface.h" #include "CredentialsInterface.h" #include "MessageInterface.h" #include "Plugin.h" #include "ScriptableObject.h" #include "IfcSecurityInterface.h" #include "SessionLostReasonInterface.h" #include "SessionOptsInterface.h" #include "SocketFdInterface.h" #include "VersionInterface.h" #include #include class _BusNamespace : public ScriptableObject { public: static std::map& Constants(); _BusNamespace(Plugin& plugin); virtual ~_BusNamespace(); private: static std::map constants; BusAttachmentInterface busAttachmentInterface; BusErrorInterface busErrorInterface; CredentialsInterface credentialsInterface; IfcSecurityInterface ifcSecurityInterface; MessageInterface messageInterface; SessionLostReasonInterface sessionLostReasonInterface; SessionOptsInterface sessionOptsInterface; SocketFdInterface socketFdInterface; VersionInterface versionInterface; bool getBusAttachment(NPVariant* result); bool getBusError(NPVariant* result); bool getCredentials(NPVariant* result); bool getIfcSecurity(NPVariant* result); bool getMessage(NPVariant* result); bool getSessionOpts(NPVariant* result); bool getSessionLostReason(NPVariant* result); bool getSocketFd(NPVariant* result); bool getVersion(NPVariant* result); /* * Fallback for FeaturePermissions APIs. * (http://dev.w3.org/2009/dap/perms/FeaturePermissions.html). */ bool getPrivilegedFeatures(NPVariant* result); bool permissionLevel(const NPVariant* args, uint32_t argCount, NPVariant* result); bool requestPermission(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_BusNamespace> BusNamespace; #endif // _BUSNAMESPACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SocketFdHost.cc0000644000175000017500000001032612620747066021454 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SocketFdHost.h" #include "TypeMapping.h" #include #include #ifndef PRIi64 #define __STDC_FORMAT_MACROS #include #endif #define QCC_MODULE "ALLJOYN_JS" _SocketFdHost::_SocketFdHost(Plugin& plugin, qcc::SocketFd& socketFd) : ScriptableObject(plugin), socketFd(socketFd) { QCC_DbgTrace(("%s(socketFd=%d)", __FUNCTION__, socketFd)); ATTRIBUTE("fd", &_SocketFdHost::getFd, 0); OPERATION("close", &_SocketFdHost::close); OPERATION("shutdown", &_SocketFdHost::shutdown); OPERATION("recv", &_SocketFdHost::recv); OPERATION("send", &_SocketFdHost::send); } _SocketFdHost::~_SocketFdHost() { QCC_DbgTrace(("%s", __FUNCTION__)); if (qcc::INVALID_SOCKET_FD != socketFd) { qcc::Close(socketFd); } } bool _SocketFdHost::getFd(NPVariant* result) { char str[32]; switch (sizeof(qcc::SocketFd)) { case 4: snprintf(str, 32, "%d", (int32_t)socketFd); break; case 8: snprintf(str, 32, "%" PRIi64, (int64_t)socketFd); break; } ToDOMString(plugin, str, strlen(str), *result); return true; } bool _SocketFdHost::close(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_DbgTrace(("%s", __FUNCTION__)); if (qcc::INVALID_SOCKET_FD != socketFd) { qcc::Close(socketFd); } socketFd = qcc::INVALID_SOCKET_FD; VOID_TO_NPVARIANT(*result); return true; } bool _SocketFdHost::shutdown(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_DbgTrace(("%s", __FUNCTION__)); ToUnsignedShort(plugin, qcc::Shutdown(socketFd), *result); return true; } bool _SocketFdHost::recv(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); bool typeError = false; NPVariant nplength = NPVARIANT_VOID; bool ignored; size_t length; uint8_t* buf = NULL; size_t i; size_t received = 0; QStatus status = ER_OK; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } if (!NPVARIANT_IS_OBJECT(args[0]) || !NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetStringIdentifier("length"), &nplength) || !(NPVARIANT_IS_INT32(nplength) || NPVARIANT_IS_DOUBLE(nplength))) { plugin->RaiseTypeError("argument 0 is not an array"); typeError = true; goto exit; } length = ToLong(plugin, nplength, ignored); buf = new uint8_t[length]; status = qcc::Recv(socketFd, buf, length, received); if (ER_OK != status) { goto exit; } for (i = 0; i < received; ++i) { NPVariant npelem = NPVARIANT_VOID; ToOctet(plugin, buf[i], npelem); bool set = NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[0]), NPN_GetIntIdentifier(i), &npelem); NPN_ReleaseVariantValue(&npelem); if (!set) { plugin->RaiseTypeError("set array element failed"); typeError = true; goto exit; } } exit: delete[] buf; NPN_ReleaseVariantValue(&nplength); if ((ER_OK == status) && !typeError) { ToUnsignedLong(plugin, received, *result); return true; } else { if (ER_OK != status) { plugin->RaiseBusError(status); } return false; } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/FeaturePermissions.cc0000644000175000017500000000535312620747066022747 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "FeaturePermissions.h" #include "PluginData.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map PluginData::permissionLevels; QStatus PluginData::PermissionLevel(Plugin& plugin, const qcc::String& feature, int32_t& level) { QCC_DbgTrace(("%s(feature=%s)", __FUNCTION__, feature.c_str())); QStatus status = ER_OK; qcc::String origin; std::map::iterator it; level = DEFAULT_DENIED; if (feature != ALLJOYN_FEATURE) { status = ER_FAIL; QCC_LogError(status, ("feature '%s' not supported", feature.c_str())); goto exit; } status = plugin->Origin(origin); if (ER_OK != status) { goto exit; } lock.Lock(); it = permissionLevels.find(origin); if (it != permissionLevels.end()) { level = it->second; QCC_DbgTrace(("Using session level %d", level)); } else { status = PersistentPermissionLevel(plugin, origin, level); if (ER_OK == status) { QCC_DbgTrace(("Using persistent level %d", level)); permissionLevels[origin] = level; } } lock.Unlock(); exit: return status; } QStatus PluginData::SetPermissionLevel(Plugin& plugin, const qcc::String& feature, int32_t level, bool remember) { QCC_DbgTrace(("SetPermissionLevel(feature=%s,level=%d,remember=%d)", feature.c_str(), level, remember)); QStatus status = ER_OK; qcc::String origin; qcc::String permission; if (feature != ALLJOYN_FEATURE) { status = ER_FAIL; QCC_LogError(status, ("feature '%s' not supported", feature.c_str())); goto exit; } status = plugin->Origin(origin); if (ER_OK != status) { goto exit; } lock.Lock(); permissionLevels[origin] = level; if (remember) { status = SetPersistentPermissionLevel(plugin, origin, level); } lock.Unlock(); exit: return status; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/ScriptableObject.cc0000644000175000017500000001402412620747066022332 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "ScriptableObject.h" #include "NativeObject.h" #include "npn.h" #include #include #include #define QCC_MODULE "ALLJOYN_JS" #define CALL_MEMBER(o, m) ((*o).*(m)) std::map ScriptableObject::noConstants; ScriptableObject::ScriptableObject(Plugin& plugin) : plugin(plugin), getter(0), setter(0), deleter(0), enumerator(0), caller(0), constants(noConstants) { QCC_DbgTrace(("%s", __FUNCTION__)); } ScriptableObject::ScriptableObject(Plugin& plugin, std::map& constants) : plugin(plugin), getter(0), setter(0), deleter(0), enumerator(0), caller(0), constants(constants) { QCC_DbgTrace(("%s", __FUNCTION__)); } ScriptableObject::~ScriptableObject() { QCC_DbgTrace(("%s", __FUNCTION__)); } void ScriptableObject::Invalidate() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool ScriptableObject::HasMethod(const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map::iterator it = operations.find(name); return (it != operations.end()); } bool ScriptableObject::Invoke(const qcc::String& name, const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map::iterator it = operations.find(name); if (it != operations.end()) { assert(it->second.call); return CALL_MEMBER(this, it->second.call) (args, argCount, result); } return false; } bool ScriptableObject::InvokeDefault(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); if (caller) { return CALL_MEMBER(this, caller) (args, argCount, result); } return false; } bool ScriptableObject::HasProperty(const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map::iterator cit = constants.find(name); if (cit != constants.end()) { return true; } std::map::iterator ait = attributes.find(name); return (ait != attributes.end()); } bool ScriptableObject::GetProperty(const qcc::String& name, NPVariant* result) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map::iterator cit = constants.find(name); if (cit != constants.end()) { INT32_TO_NPVARIANT(cit->second, *result); return true; } std::map::iterator ait = attributes.find(name); if (ait != attributes.end()) { assert(ait->second.get); return CALL_MEMBER(this, ait->second.get) (result); } if (getter) { return CALL_MEMBER(this, getter) (name, result); } return false; } bool ScriptableObject::SetProperty(const qcc::String& name, const NPVariant* value) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); /* * Workaround for WebKit browsers. "delete obj.property" doesn't call RemoveProperty, so allow * "obj.property = undefined" to do the same thing. */ if (NPVARIANT_IS_VOID(*value)) { return RemoveProperty(name); } std::map::iterator it = attributes.find(name); if ((it != attributes.end()) && it->second.set) { return CALL_MEMBER(this, it->second.set) (value); } if (setter) { return CALL_MEMBER(this, setter) (name, value); } return false; } bool ScriptableObject::RemoveProperty(const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); if (deleter) { return CALL_MEMBER(this, deleter) (name); } return false; } bool ScriptableObject::Enumerate(NPIdentifier** value, uint32_t* count) { QCC_DbgTrace(("%s", __FUNCTION__)); *value = NULL; *count = 0; NPIdentifier* enumeratorValue = NULL; uint32_t enumeratorCount = 0; if (enumerator) { CALL_MEMBER(this, enumerator) (&enumeratorValue, &enumeratorCount); } *count = enumeratorCount + constants.size() + attributes.size() + operations.size(); if (*count) { *value = reinterpret_cast(NPN_MemAlloc(*count * sizeof(NPIdentifier))); NPIdentifier* v = *value; for (uint32_t i = 0; i < enumeratorCount; ++i) { *v++ = enumeratorValue[i]; } if (enumeratorValue) { NPN_MemFree(enumeratorValue); } for (std::map::iterator it = constants.begin(); it != constants.end(); ++it) { *v++ = NPN_GetStringIdentifier(it->first.c_str()); } for (std::map::iterator it = attributes.begin(); it != attributes.end(); ++it) { *v++ = NPN_GetStringIdentifier(it->first.c_str()); } for (std::map::iterator it = operations.begin(); it != operations.end(); ++it) { *v++ = NPN_GetStringIdentifier(it->first.c_str()); } } return true; } bool ScriptableObject::Construct(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_UNUSED(result); QCC_DbgTrace(("%s", __FUNCTION__)); return false; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/Plugin.cc0000644000175000017500000000535112620747066020354 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Plugin.h" #include "TypeMapping.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" _Plugin::_Plugin(NPP npp) : npp(npp) { QCC_DbgTrace(("%s", __FUNCTION__)); } _Plugin::_Plugin() : npp(0) { QCC_DbgTrace(("%s", __FUNCTION__)); } _Plugin::~_Plugin() { QCC_DbgTrace(("%s", __FUNCTION__)); } qcc::String _Plugin::ToFilename(const qcc::String& in) { qcc::String url = in; QCC_DbgPrintf(("unencoded url=%s", url.c_str())); for (size_t i = 0; i < url.size(); ++i) { switch (url[i]) { case '$': case '-': case '_': case '.': case '+': case '!': case '*': case '\'': case '(': case ')': case ',': case ';': case '/': case '?': case ':': case '@': case '=': case '&': { char encoded[3]; snprintf(encoded, 3, "%02X", url[i]); url[i] = '%'; url.insert(i + 1, encoded, 2); i += 2; break; } default: /* Do nothing */ break; } } QCC_DbgPrintf(("encoded url=%s", url.c_str())); return url; } bool _Plugin::RaiseBusError(QStatus code, const char* message) { _error.name = "BusError"; _error.message = message; _error.code = code; QCC_LogError(_error.code, ("%s: %s", _error.name.c_str(), _error.message.c_str())); return false; } bool _Plugin::RaiseTypeError(const char* message) { _error.name = "TypeError"; _error.message = message; QCC_LogError(_error.code, ("%s: %s", _error.name.c_str(), _error.message.c_str())); return false; } void _Plugin::CheckError(NPObject* npobj) { if (!_error.name.empty()) { error = _error; _error.Clear(); NPN_SetException(npobj, error.name.c_str()); } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AuthListenerNative.cc0000644000175000017500000001173612620747066022700 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "AuthListenerNative.h" #include "BusAttachmentHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" AuthListenerNative::AuthListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } AuthListenerNative::~AuthListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool AuthListenerNative::onRequest(qcc::String& authMechanism, qcc::String& peerName, uint16_t authCount, qcc::String& userName, uint16_t credMask, CredentialsHost& credentials) { QCC_DbgTrace(("%s", __FUNCTION__)); bool requested = false; NPIdentifier onRequest = NPN_GetStringIdentifier("onRequest"); if (NPN_HasMethod(plugin->npp, objectValue, onRequest)) { NPVariant npargs[6]; ToDOMString(plugin, authMechanism, npargs[0]); ToDOMString(plugin, peerName, npargs[1]); ToUnsignedShort(plugin, authCount, npargs[2]); ToDOMString(plugin, userName, npargs[3]); ToUnsignedShort(plugin, credMask, npargs[4]); ToHostObject(plugin, credentials, npargs[5]); NPVariant result = NPVARIANT_VOID; if (NPN_Invoke(plugin->npp, objectValue, onRequest, npargs, 6, &result)) { bool ignore; requested = ToBoolean(plugin, result, ignore); } else { QCC_LogError(ER_FAIL, ("NPN_Invoke failed")); } NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[5]); NPN_ReleaseVariantValue(&npargs[3]); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&npargs[0]); } else { QCC_LogError(ER_FAIL, ("No such method 'onRequest'")); } return requested; } bool AuthListenerNative::onVerify(qcc::String& authMechanism, qcc::String& peerName, CredentialsHost& credentials) { QCC_DbgTrace(("%s", __FUNCTION__)); bool verified = false; NPIdentifier onVerify = NPN_GetStringIdentifier("onVerify"); if (NPN_HasMethod(plugin->npp, objectValue, onVerify)) { NPVariant npargs[3]; ToDOMString(plugin, authMechanism, npargs[0]); ToDOMString(plugin, peerName, npargs[1]); ToHostObject(plugin, credentials, npargs[2]); NPVariant result = NPVARIANT_VOID; if (NPN_Invoke(plugin->npp, objectValue, onVerify, npargs, 3, &result)) { bool ignore; verified = ToBoolean(plugin, result, ignore); } else { QCC_LogError(ER_FAIL, ("NPN_Invoke failed")); } NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&npargs[0]); } else { QCC_LogError(ER_FAIL, ("No such method 'onVerify'")); } return verified; } void AuthListenerNative::onSecurityViolation(QStatus status, MessageHost& message) { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onSecurityViolation = NPN_GetStringIdentifier("onSecurityViolation"); if (NPN_HasMethod(plugin->npp, objectValue, onSecurityViolation)) { NPVariant npargs[2]; ToUnsignedShort(plugin, status, npargs[0]); ToHostObject(plugin, message, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onSecurityViolation, npargs, 2, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[1]); } } void AuthListenerNative::onComplete(qcc::String& authMechanism, qcc::String& peerName, bool success) { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onComplete = NPN_GetStringIdentifier("onComplete"); if (NPN_HasMethod(plugin->npp, objectValue, onComplete)) { NPVariant npargs[3]; ToDOMString(plugin, authMechanism, npargs[0]); ToDOMString(plugin, peerName, npargs[1]); ToBoolean(plugin, success, npargs[2]); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onComplete, npargs, 3, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&npargs[0]); } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageInterface.cc0000644000175000017500000000330012620747066022313 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "MessageInterface.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _MessageInterface::constants; std::map& _MessageInterface::Constants() { if (constants.empty()) { CONSTANT("ALLJOYN_FLAG_NO_REPLY_EXPECTED", 0x01); CONSTANT("ALLJOYN_FLAG_AUTO_START", 0x02); CONSTANT("ALLJOYN_FLAG_ALLOW_REMOTE_MSG", 0x04); CONSTANT("ALLJOYN_FLAG_SESSIONLESS", 0x10); CONSTANT("ALLJOYN_FLAG_GLOBAL_BROADCAST", 0x20); CONSTANT("ALLJOYN_FLAG_COMPRESSED", 0x40); CONSTANT("ALLJOYN_FLAG_ENCRYPTED", 0x80); } return constants; } _MessageInterface::_MessageInterface(Plugin& plugin) : ScriptableObject(plugin, Constants()) { QCC_DbgTrace(("%s", __FUNCTION__)); } _MessageInterface::~_MessageInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/Status.xml0000644000175000017500000000170312620747066020611 0ustar debiandebian alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusListenerNative.h0000644000175000017500000000334112620747066022363 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSLISTENERNATIVE_H #define _BUSLISTENERNATIVE_H #include "BusAttachmentHost.h" #include "NativeObject.h" #include #include class BusListenerNative : public NativeObject { public: BusListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~BusListenerNative(); void onRegistered(BusAttachmentHost& busAttachment); void onUnregistered(); void onFoundAdvertisedName(const qcc::String& name, ajn::TransportMask transport, const qcc::String& namePrefix); void onLostAdvertisedName(const qcc::String& name, ajn::TransportMask transport, const qcc::String& namePrefix); void onNameOwnerChanged(const qcc::String& busName, const qcc::String& previousOwner, const qcc::String& newOwner); void onPropertyChanged(const qcc::String& propName, const ajn::MsgArg* propValue); void onStopping(); void onDisconnected(); }; #endif // _BUSLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HostObject.h0000644000175000017500000002351712620747066021030 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _HOSTOBJECT_H #define _HOSTOBJECT_H #include "Plugin.h" #include "PluginData.h" #include #include template class HostObject : public NPObject { public: static HostObject* GetInstance(Plugin& plugin, T& impl); static T* GetImpl(Plugin& plugin, NPObject* npobj); static NPClass Class; private: static NPObject* Allocate(NPP npp, NPClass* aClass); static void Deallocate(NPObject* npobj); static void Invalidate(NPObject* npobj); static bool HasMethod(NPObject* npobj, NPIdentifier name); static bool Invoke(NPObject* npobj, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result); static bool InvokeDefault(NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result); static bool HasProperty(NPObject* npobj, NPIdentifier name); static bool GetProperty(NPObject* npobj, NPIdentifier name, NPVariant* result); static bool SetProperty(NPObject* npobj, NPIdentifier name, const NPVariant* value); static bool RemoveProperty(NPObject* npobj, NPIdentifier name); static bool Enumerate(NPObject* npobj, NPIdentifier** value, uint32_t* count); static bool Construct(NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result); HostObject(Plugin& plugin, T& impl); ~HostObject(); Plugin plugin; T impl; }; #define QCC_MODULE "ALLJOYN_JS" template NPClass HostObject::Class = { NP_CLASS_STRUCT_VERSION_CTOR, HostObject::Allocate, HostObject::Deallocate, HostObject::Invalidate, HostObject::HasMethod, HostObject::Invoke, HostObject::InvokeDefault, HostObject::HasProperty, HostObject::GetProperty, HostObject::SetProperty, HostObject::RemoveProperty, HostObject::Enumerate, HostObject::Construct, }; template HostObject* HostObject::GetInstance(Plugin& plugin, T& impl) { ScriptableObject* obj = static_cast(&(*impl)); std::map::iterator it = plugin->hostObjects.find(obj); NPObject* npobj; if (it != plugin->hostObjects.end()) { npobj = NPN_RetainObject(it->second); QCC_DbgTrace(("%s returning cached object %p", __FUNCTION__, npobj)); } else { plugin->params = &impl; npobj = NPN_CreateObject(plugin->npp, &HostObject::Class); QCC_DbgTrace(("%s returning new object %p", __FUNCTION__, npobj)); } return static_cast*>(npobj); } template T* HostObject::GetImpl(Plugin& plugin, NPObject* npobj) { QCC_UNUSED(plugin); assert(&HostObject::Class == npobj->_class); HostObject* obj = static_cast*>(npobj); return &obj->impl; } template NPObject* HostObject::Allocate(NPP npp, NPClass* aClass) { QCC_UNUSED(aClass); //aClass only used in debug build QCC_DbgTrace(("%s(npp=%p,aClass=%p)", __FUNCTION__, npp, aClass)); PluginData* pluginData = reinterpret_cast(npp->pdata); Plugin& plugin = pluginData->GetPlugin(); T* impl = reinterpret_cast(plugin->params); NPObject* npobj = static_cast(new HostObject(plugin, *impl)); plugin->hostObjects[static_cast(&(**impl))] = npobj; QCC_DbgTrace(("%s npobj=%p", __FUNCTION__, npobj)); PluginData::InsertNPObject(npobj); return npobj; } template void HostObject::Deallocate(NPObject* npobj) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); HostObject* obj = static_cast*>(npobj); obj->plugin->hostObjects.erase(&(*obj->impl)); PluginData::RemoveNPObject(npobj); delete obj; } template void HostObject::Invalidate(NPObject* npobj) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); HostObject* obj = static_cast*>(npobj); obj->impl->Invalidate(); } template bool HostObject::HasMethod(NPObject* npobj, NPIdentifier name) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); if (!NPN_IdentifierIsString(name)) { QCC_LogError(ER_FAIL, ("HasMethod called with int identifier")); return false; } NPUTF8* nm = NPN_UTF8FromIdentifier(name); if (!nm) { QCC_LogError(ER_OUT_OF_MEMORY, ("NPN_UTF8FromIdentifier failed")); return false; } HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->HasMethod(nm); NPN_MemFree(nm); obj->plugin->CheckError(obj); return ret; } template bool HostObject::Invoke(NPObject* npobj, NPIdentifier name, const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); if (!NPN_IdentifierIsString(name)) { QCC_LogError(ER_FAIL, ("HasMethod called with int identifier")); return false; } NPUTF8* nm = NPN_UTF8FromIdentifier(name); if (!nm) { QCC_LogError(ER_OUT_OF_MEMORY, ("NPN_UTF8FromIdentifier failed")); return false; } HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->Invoke(nm, args, argCount, result); NPN_MemFree(nm); obj->plugin->CheckError(obj); return ret; } template bool HostObject::InvokeDefault(NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->InvokeDefault(args, argCount, result); obj->plugin->CheckError(obj); return ret; } template bool HostObject::HasProperty(NPObject* npobj, NPIdentifier name) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); if (!NPN_IdentifierIsString(name)) { QCC_LogError(ER_FAIL, ("HasMethod called with int identifier")); return false; } NPUTF8* nm = NPN_UTF8FromIdentifier(name); if (!nm) { QCC_LogError(ER_OUT_OF_MEMORY, ("NPN_UTF8FromIdentifier failed")); return false; } HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->HasProperty(nm); NPN_MemFree(nm); obj->plugin->CheckError(obj); return ret; } template bool HostObject::GetProperty(NPObject* npobj, NPIdentifier name, NPVariant* result) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); if (!NPN_IdentifierIsString(name)) { QCC_LogError(ER_FAIL, ("HasMethod called with int identifier")); return false; } NPUTF8* nm = NPN_UTF8FromIdentifier(name); if (!nm) { QCC_LogError(ER_OUT_OF_MEMORY, ("NPN_UTF8FromIdentifier failed")); return false; } HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->GetProperty(nm, result); NPN_MemFree(nm); obj->plugin->CheckError(obj); return ret; } template bool HostObject::SetProperty(NPObject* npobj, NPIdentifier name, const NPVariant* value) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); if (!NPN_IdentifierIsString(name)) { QCC_LogError(ER_FAIL, ("HasMethod called with int identifier")); return false; } NPUTF8* nm = NPN_UTF8FromIdentifier(name); if (!nm) { QCC_LogError(ER_OUT_OF_MEMORY, ("NPN_UTF8FromIdentifier failed")); return false; } HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->SetProperty(nm, value); NPN_MemFree(nm); obj->plugin->CheckError(obj); return ret; } template bool HostObject::RemoveProperty(NPObject* npobj, NPIdentifier name) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); if (!NPN_IdentifierIsString(name)) { QCC_LogError(ER_FAIL, ("HasMethod called with int identifier")); return false; } NPUTF8* nm = NPN_UTF8FromIdentifier(name); if (!nm) { QCC_LogError(ER_OUT_OF_MEMORY, ("NPN_UTF8FromIdentifier failed")); return false; } HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->RemoveProperty(nm); NPN_MemFree(nm); obj->plugin->CheckError(obj); return ret; } template bool HostObject::Enumerate(NPObject* npobj, NPIdentifier** value, uint32_t* count) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->Enumerate(value, count); obj->plugin->CheckError(obj); return ret; } template bool HostObject::Construct(NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s(npobj=%p)", __FUNCTION__, npobj)); HostObject* obj = static_cast*>(npobj); bool ret = obj->impl->Construct(args, argCount, result); obj->plugin->CheckError(obj); return ret; } template HostObject::HostObject(Plugin& plugin, T& impl) : plugin(plugin), impl(impl) { QCC_DbgTrace(("%s", __FUNCTION__)); } template HostObject::~HostObject() { QCC_DbgTrace(("%s", __FUNCTION__)); } #undef QCC_MODULE #endif // _HOSTOBJECT_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/VersionInterface.cc0000644000175000017500000000474012620747066022365 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "VersionInterface.h" #include "npn.h" #include "TypeMapping.h" #include #include #include #define QCC_MODULE "ALLJOYN_JS" _VersionInterface::_VersionInterface(Plugin& plugin) : ScriptableObject(plugin) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("buildInfo", &_VersionInterface::getBuildInfo, 0); ATTRIBUTE("numericVersion", &_VersionInterface::getNumericVersion, 0); ATTRIBUTE("arch", &_VersionInterface::getArch, 0); ATTRIBUTE("apiLevel", &_VersionInterface::getApiLevel, 0); ATTRIBUTE("release", &_VersionInterface::getRelease, 0); ATTRIBUTE("version", &_VersionInterface::getVersion, 0); } _VersionInterface::~_VersionInterface() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _VersionInterface::getBuildInfo(NPVariant* result) { ToDOMString(plugin, ajn::GetBuildInfo(), strlen(ajn::GetBuildInfo()), *result); return true; } bool _VersionInterface::getNumericVersion(NPVariant* result) { ToUnsignedLong(plugin, ajn::GetNumericVersion(), *result); return true; } bool _VersionInterface::getArch(NPVariant* result) { ToUnsignedLong(plugin, GetVersionArch(ajn::GetNumericVersion()), *result); return true; } bool _VersionInterface::getApiLevel(NPVariant* result) { ToUnsignedLong(plugin, GetVersionAPILevel(ajn::GetNumericVersion()), *result); return true; } bool _VersionInterface::getRelease(NPVariant* result) { ToUnsignedLong(plugin, GetVersionRelease(ajn::GetNumericVersion()), *result); return true; } bool _VersionInterface::getVersion(NPVariant* result) { ToDOMString(plugin, ajn::GetVersion(), strlen(ajn::GetVersion()), *result); return true; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusObject.h0000644000175000017500000001061112620747066020633 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSOBJECT_H #define _BUSOBJECT_H #include "BusAttachment.h" #include class _BusObjectListener { public: virtual ~_BusObjectListener() { } virtual QStatus Get(const char* ifcName, const char* propName, ajn::MsgArg& val) = 0; virtual QStatus Set(const char* ifcName, const char* propName, ajn::MsgArg& val) = 0; virtual QStatus GenerateIntrospection(bool deep, size_t indent, qcc::String& introspection) const = 0; virtual void ObjectRegistered() = 0; virtual void ObjectUnregistered() = 0; virtual void MethodHandler(const ajn::InterfaceDescription::Member* member, ajn::Message& message) = 0; }; class _BusObject : public ajn::BusObject { public: _BusObject(BusAttachment& busAttachment, const char* path) : ajn::BusObject(path), busAttachment(busAttachment), busObjectListener(NULL) { } virtual ~_BusObject() { } void SetBusObjectListener(_BusObjectListener* busObjectListener) { this->busObjectListener = busObjectListener; } BusAttachment busAttachment; QStatus AddInterface(const ajn::InterfaceDescription& iface, const AnnounceFlag isAnnounced) { return ajn::BusObject::AddInterface(iface, isAnnounced); } QStatus AddMethodHandler(const ajn::InterfaceDescription::Member* member) { return ajn::BusObject::AddMethodHandler(member, static_cast(&_BusObject::MethodHandler)); } QStatus MethodReply(ajn::Message& msg, const ajn::MsgArg* args = NULL, size_t numArgs = 0) { return ajn::BusObject::MethodReply(msg, args, numArgs); } QStatus MethodReply(ajn::Message& msg, const char* error, const char* errorMessage = NULL) { return ajn::BusObject::MethodReply(msg, error, errorMessage); } QStatus MethodReply(ajn::Message& msg, QStatus status) { return ajn::BusObject::MethodReply(msg, status); } QStatus Signal(const char* destination, ajn::SessionId sessionId, const ajn::InterfaceDescription::Member& signal, const ajn::MsgArg* args = NULL, size_t numArgs = 0, uint16_t timeToLive = 0, uint8_t flags = 0) { return ajn::BusObject::Signal(destination, sessionId, signal, args, numArgs, timeToLive, flags); } private: _BusObjectListener* busObjectListener; virtual QStatus Get(const char* ifcName, const char* propName, ajn::MsgArg& val) { return busObjectListener ? busObjectListener->Get(ifcName, propName, val) : ER_FAIL; } virtual QStatus Set(const char* ifcName, const char* propName, ajn::MsgArg& val) { return busObjectListener ? busObjectListener->Set(ifcName, propName, val) : ER_FAIL; } virtual qcc::String GenerateIntrospection(bool deep = false, size_t indent = 0) const { qcc::String introspection; if (!busObjectListener || (ER_OK != busObjectListener->GenerateIntrospection(deep, indent, introspection))) { return ajn::BusObject::GenerateIntrospection(deep, indent); } return introspection; } virtual void ObjectRegistered() { ajn::BusObject::ObjectRegistered(); if (busObjectListener) { busObjectListener->ObjectRegistered(); } } virtual void ObjectUnregistered() { ajn::BusObject::ObjectUnregistered(); if (busObjectListener) { busObjectListener->ObjectUnregistered(); } } void MethodHandler(const ajn::InterfaceDescription::Member* member, ajn::Message& message) { if (busObjectListener) { busObjectListener->MethodHandler(member, message); } else { MethodReply(message, ER_FAIL); } } }; typedef qcc::ManagedObj<_BusObject> BusObject; #endif alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HttpServer.h0000644000175000017500000000741212620747066021066 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _HTTPSERVER_H #define _HTTPSERVER_H #include "Plugin.h" #include #include #include #include #include #include class HttpListenerNative; namespace Http { struct less { bool operator()(const qcc::String& a, const qcc::String& b) const { return strcasecmp(a.c_str(), b.c_str()) < 0; } }; typedef std::map Headers; } /* * Some care needs to be taken to ensure that a rogue entity cannot intercept the raw session data. * This consists of two parts: a shared secret (the request URI) that is transmitted over a secure * channel (the NPAPI interface), and an encrypted connection between the HTTP server and the * requestor. * * This means the rogue entity cannot sniff the generated URI, so the chance of them circumventing * the security is limited to brute-forcing a 256 bit key. * * TODO This second part is not yet implemented. */ class _HttpServer : public qcc::Thread, public qcc::ThreadListener { public: _HttpServer(Plugin& plugin); virtual ~_HttpServer(); virtual void ThreadExit(qcc::Thread* thread); QStatus CreateObjectUrl(qcc::SocketFd fd, HttpListenerNative* httpListener, qcc::String& url); void RevokeObjectUrl(const qcc::String& url); class ObjectUrl { public: qcc::SocketFd fd; HttpListenerNative* httpListener; ObjectUrl() : fd(qcc::INVALID_SOCKET_FD), httpListener(NULL) { } ObjectUrl(qcc::SocketFd fd, HttpListenerNative* httpListener) : fd(fd), httpListener(httpListener) { } }; ObjectUrl GetObjectUrl(const qcc::String& requestUri); void SendResponse(qcc::SocketStream& stream, uint16_t status, qcc::String& statusText, Http::Headers& responseHeaders, qcc::SocketFd fd); protected: virtual qcc::ThreadReturn STDCALL Run(void* arg); private: class RequestThread : public qcc::Thread { public: RequestThread(_HttpServer* httpServer, qcc::SocketFd fd); virtual ~RequestThread() { } protected: virtual qcc::ThreadReturn STDCALL Run(void* arg); private: _HttpServer* httpServer; qcc::SocketStream stream; }; class ResponseThread : public qcc::Thread { public: ResponseThread(_HttpServer* httpServer, qcc::SocketStream& stream, uint16_t status, qcc::String& statusText, Http::Headers& responseHeaders, qcc::SocketFd sessionFd); virtual ~ResponseThread() { } protected: virtual qcc::ThreadReturn STDCALL Run(void* arg); private: _HttpServer* httpServer; qcc::SocketStream stream; uint16_t status; qcc::String statusText; Http::Headers responseHeaders; qcc::SocketFd sessionFd; }; Plugin plugin; qcc::String origin; std::map objectUrls; qcc::Mutex lock; std::vector threads; QStatus Start(); }; typedef qcc::ManagedObj<_HttpServer> HttpServer; #endif alljoyn-15.09a+dfsg.1/alljoyn_js/jni/.gitignore0000644000175000017500000000002512620747066020570 0ustar debiandebianBusErrorInterface.cc alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusNamespace.cc0000644000175000017500000002073612620747066021470 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "BusNamespace.h" #include "FeaturePermissions.h" #include "HostObject.h" #include "SuccessListenerNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" std::map _BusNamespace::constants; std::map& _BusNamespace::Constants() { if (constants.empty()) { CONSTANT("USER_ALLOWED", USER_ALLOWED); CONSTANT("DEFAULT_ALLOWED", DEFAULT_ALLOWED); CONSTANT("DEFAULT_DENIED", DEFAULT_DENIED); CONSTANT("USER_DENIED", USER_DENIED); } return constants; } _BusNamespace::_BusNamespace(Plugin& plugin) : ScriptableObject(plugin, Constants()), busAttachmentInterface(plugin), busErrorInterface(plugin), credentialsInterface(plugin), ifcSecurityInterface(plugin), messageInterface(plugin), sessionLostReasonInterface(plugin), sessionOptsInterface(plugin), socketFdInterface(plugin), versionInterface(plugin) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("BusAttachment", &_BusNamespace::getBusAttachment, 0); ATTRIBUTE("BusError", &_BusNamespace::getBusError, 0); ATTRIBUTE("Credentials", &_BusNamespace::getCredentials, 0); ATTRIBUTE("IfcSecurity", &_BusNamespace::getIfcSecurity, 0); ATTRIBUTE("Message", &_BusNamespace::getMessage, 0); ATTRIBUTE("SessionLostReason", &_BusNamespace::getSessionLostReason, 0); ATTRIBUTE("SessionOpts", &_BusNamespace::getSessionOpts, 0); ATTRIBUTE("SocketFd", &_BusNamespace::getSocketFd, 0); ATTRIBUTE("Version", &_BusNamespace::getVersion, 0); ATTRIBUTE("privilegedFeatures", &_BusNamespace::getPrivilegedFeatures, 0); OPERATION("permissionLevel", &_BusNamespace::permissionLevel); OPERATION("requestPermission", &_BusNamespace::requestPermission); } _BusNamespace::~_BusNamespace() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _BusNamespace::getBusAttachment(NPVariant* result) { ToHostObject(plugin, busAttachmentInterface, *result); return true; } bool _BusNamespace::getBusError(NPVariant* result) { ToHostObject(plugin, busErrorInterface, *result); return true; } bool _BusNamespace::getCredentials(NPVariant* result) { ToHostObject(plugin, credentialsInterface, *result); return true; } bool _BusNamespace::getIfcSecurity(NPVariant* result) { ToHostObject(plugin, ifcSecurityInterface, *result); return true; } bool _BusNamespace::getMessage(NPVariant* result) { ToHostObject(plugin, messageInterface, *result); return true; } bool _BusNamespace::getSessionLostReason(NPVariant* result) { ToHostObject(plugin, sessionLostReasonInterface, *result); return true; } bool _BusNamespace::getSessionOpts(NPVariant* result) { ToHostObject(plugin, sessionOptsInterface, *result); return true; } bool _BusNamespace::getSocketFd(NPVariant* result) { ToHostObject(plugin, socketFdInterface, *result); return true; } bool _BusNamespace::getVersion(NPVariant* result) { ToHostObject(plugin, versionInterface, *result); return true; } bool _BusNamespace::getPrivilegedFeatures(NPVariant* result) { VOID_TO_NPVARIANT(*result); if (NewArray(plugin, *result)) { NPVariant element = NPVARIANT_VOID; ToDOMString(plugin, ALLJOYN_FEATURE, element); if (!NPN_SetProperty(plugin->npp, NPVARIANT_TO_OBJECT(*result), NPN_GetIntIdentifier(0), &element)) { QCC_LogError(ER_FAIL, ("NPN_SetProperty failed")); } NPN_ReleaseVariantValue(&element); } else { QCC_LogError(ER_FAIL, ("NewArray failed")); } return true; } bool _BusNamespace::permissionLevel(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String feature; int32_t level; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } feature = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } status = PluginData::PermissionLevel(plugin, feature, level); exit: if ((ER_OK == status) && !typeError) { ToLong(plugin, level, *result); return true; } else { if (ER_OK != status) { plugin->RaiseBusError(status); } return false; } } class RequestPermissionAsyncCB : public RequestPermissionListener { public: class _Env { public: Plugin plugin; qcc::String feature; SuccessListenerNative* callbackNative; _Env(Plugin& plugin, qcc::String& feature, SuccessListenerNative* callbackNative) : plugin(plugin), feature(feature), callbackNative(callbackNative) { } ~_Env() { delete callbackNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; RequestPermissionAsyncCB(Plugin& plugin, qcc::String& feature, SuccessListenerNative* callbackNative) : env(plugin, feature, callbackNative) { QCC_DbgTrace(("%s", __FUNCTION__)); } virtual ~RequestPermissionAsyncCB() { QCC_DbgTrace(("%s", __FUNCTION__)); } class RequestPermissionCBContext : public PluginData::CallbackContext { public: Env env; int32_t level; bool remember; RequestPermissionCBContext(Env& env, int32_t level, bool remember) : env(env), level(level), remember(remember) { } }; virtual void RequestPermissionCB(int32_t level, bool remember) { PluginData::Callback callback(env->plugin, _RequestPermissionCB); callback->context = new RequestPermissionCBContext(env, level, remember); delete this; PluginData::DispatchCallback(callback); } static void _RequestPermissionCB(PluginData::CallbackContext* ctx) { RequestPermissionCBContext* context = static_cast(ctx); PluginData::SetPermissionLevel(context->env->plugin, context->env->feature, context->level, context->remember); context->env->callbackNative->onSuccess(); } }; bool _BusNamespace::requestPermission(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; qcc::String feature; SuccessListenerNative* callbackNative = NULL; RequestPermissionAsyncCB* callback = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } feature = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } callback = new RequestPermissionAsyncCB(plugin, feature, callbackNative); callbackNative = NULL; /* callback now owns callbackNative */ status = RequestPermission(plugin, feature, callback); if (ER_OK == status) { callback = NULL; /* request now owns callback */ } exit: delete callback; delete callbackNative; if ((ER_OK == status) && !typeError) { VOID_TO_NPVARIANT(*result); return true; } else { if (ER_OK != status) { plugin->RaiseBusError(status); } return false; } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusErrorInterface.h0000644000175000017500000000260312620747066022341 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _BUSERRORINTERFACE_H #define _BUSERRORINTERFACE_H #include "ScriptableObject.h" #include class _BusErrorInterface : public ScriptableObject { public: static std::map& Constants(); _BusErrorInterface(Plugin& plugin); virtual ~_BusErrorInterface(); private: static std::map constants; bool getName(NPVariant* result); bool getMessage(NPVariant* result); bool getCode(NPVariant* result); }; typedef qcc::ManagedObj<_BusErrorInterface> BusErrorInterface; #endif // _BUSERRORINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/MessageInterface.h0000644000175000017500000000241112620747066022157 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _MESSAGEINTERFACE_H #define _MESSAGEINTERFACE_H #include "ScriptableObject.h" #include class _MessageInterface : public ScriptableObject { public: static std::map& Constants(); _MessageInterface(Plugin& plugin); virtual ~_MessageInterface(); private: static std::map constants; }; typedef qcc::ManagedObj<_MessageInterface> MessageInterface; #endif // _MESSAGEINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionLostListenerNative.cc0000644000175000017500000000320012620747066024247 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionLostListenerNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" SessionLostListenerNative::SessionLostListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } SessionLostListenerNative::~SessionLostListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void SessionLostListenerNative::onLost(ajn::SessionId id, ajn::SessionListener::SessionLostReason reason) { QCC_DbgTrace(("%s(id=%u, reason=%u)", __FUNCTION__, id, reason)); NPVariant npargs[2]; ToUnsignedLong(plugin, id, npargs[0]); ToUnsignedLong(plugin, reason, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HttpListenerNative.cc0000644000175000017500000000317412620747066022713 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "HttpListenerNative.h" #include "HttpRequestHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" HttpListenerNative::HttpListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } HttpListenerNative::~HttpListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void HttpListenerNative::onRequest(HttpRequestHost& request) { QCC_DbgTrace(("%s", __FUNCTION__)); NPVariant nparg; ToHostObject(plugin, request, nparg); NPVariant result = NPVARIANT_VOID; if (!NPN_InvokeDefault(plugin->npp, objectValue, &nparg, 1, &result)) { QCC_LogError(ER_FAIL, ("NPN_InvokeDefault failed")); } NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&nparg); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/0000755000175000017500000000000012620747066017224 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/linux/0000755000175000017500000000000012620747066020363 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/linux/BusAttachmentHost.cc0000644000175000017500000000206012620747066024270 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../BusAttachmentHost.h" #include #define QCC_MODULE "ALLJOYN_JS" QStatus _BusAttachmentHost::Connect(Plugin& plugin, const char* connectSpec) { QCC_UNUSED(plugin); return (*busAttachment)->Connect(connectSpec); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/linux/FeaturePermissions.cc0000644000175000017500000001112412620747066024520 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../FeaturePermissions.h" #include "../../PluginData.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" QStatus RequestPermission(Plugin& plugin, const qcc::String& feature, RequestPermissionListener* listener) { QCC_DbgTrace(("RequestPermission(feature=%s,listener=%p)", feature.c_str(), listener)); QStatus status = ER_OK; int32_t level; qcc::String origin; status = PluginData::PermissionLevel(plugin, feature, level); if (ER_OK != status) { goto exit; } if (DEFAULT_DENIED != level) { listener->RequestPermissionCB(level, false); goto exit; } if (feature != ALLJOYN_FEATURE) { status = ER_FAIL; QCC_LogError(status, ("feature '%s' not supported", feature.c_str())); goto exit; } status = plugin->Origin(origin); if (ER_OK != status) { goto exit; } /* * TODO Implement the request permission dialog. */ listener->RequestPermissionCB(DEFAULT_ALLOWED, false); exit: return status; } QStatus PersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t& level) { /* * TODO Level should be DEFAULT_DENIED in a complete implementation. See TODO above. */ level = DEFAULT_ALLOWED; qcc::String filename = qcc::GetHomeDir() + "/.alljoyn_keystore/" + plugin->ToFilename(origin) + "_permission"; QCC_DbgTrace(("filename=%s", filename.c_str())); qcc::FileSource source(filename); if (source.IsValid()) { source.Lock(true); qcc::String permission; source.GetLine(permission); source.Unlock(); QCC_DbgHLPrintf(("Read permission '%s' from %s", permission.c_str(), filename.c_str())); qcc::String levelString = qcc::Trim(permission); if (levelString == "USER_ALLOWED") { level = USER_ALLOWED; } else if (levelString == "USER_DENIED") { level = USER_DENIED; } else if (levelString == "DEFAULT_ALLOWED") { level = DEFAULT_ALLOWED; } } return ER_OK; } QStatus SetPersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t level) { QStatus status = ER_OK; qcc::String filename = qcc::GetHomeDir() + "/.alljoyn_keystore/" + plugin->ToFilename(origin) + "_permission"; qcc::FileSink sink(filename, qcc::FileSink::PRIVATE); if (sink.IsValid()) { sink.Lock(true); qcc::String permission; /* * Why the '\n' below? FileSink doesn't truncate the existing file, so the line-break * ensures that we don't get any characters leftover from a previous write for a longer * string than the current one. */ switch (level) { case USER_ALLOWED: permission = "USER_ALLOWED\n"; break; case DEFAULT_ALLOWED: permission = "DEFAULT_ALLOWED\n"; break; case DEFAULT_DENIED: permission = "DEFAULT_DENIED\n"; break; case USER_DENIED: permission = "USER_DENIED\n"; break; } size_t bytesWritten; status = sink.PushBytes(permission.c_str(), permission.size(), bytesWritten); if (ER_OK == status) { if (permission.size() == bytesWritten) { QCC_DbgHLPrintf(("Wrote permission '%s' to %s", qcc::Trim(permission).c_str(), filename.c_str())); } else { status = ER_BUS_WRITE_ERROR; QCC_LogError(status, ("Cannot write permission to %s", filename.c_str())); } } sink.Unlock(); } else { status = ER_BUS_WRITE_ERROR; QCC_LogError(status, ("Cannot write permission to %s", filename.c_str())); } return status; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/windows/0000755000175000017500000000000012620747066020716 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/windows/BusAttachmentHost.cc0000644000175000017500000000203012620747066024620 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../BusAttachmentHost.h" #include #define QCC_MODULE "ALLJOYN_JS" QStatus _BusAttachmentHost::Connect(Plugin& plugin, const char* connectSpec) { return (*busAttachment)->Connect(connectSpec); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/windows/resource.h0000644000175000017500000000177312620747066022726 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _RESOURCE_H #define _RESOURCE_H #define IDD_PERMISSIONREQ 103 #define IDC_REMEMBER 1000 #define IDC_ORIGIN 1004 #endif // _RESOURCE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/windows/npalljoyn.rc0000644000175000017500000000520512620747066023254 0ustar debiandebian///////////////////////////////////////////////////////////////////////////// // Copyright AllSeen Alliance. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include #include "resource.h" #ifdef IDC_STATIC #undef IDC_STATIC #endif #define IDC_STATIC (-1) ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 15,9,0,97 PRODUCTVERSION 15,9,0,97 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904e4" BEGIN VALUE "CompanyName", "AllSeen Alliance." VALUE "FileDescription", L"AllJoyn browser plugin" VALUE "FileVersion", "15.09.00a" VALUE "InternalName", "npalljoyn" VALUE "LegalCopyright", "Copyright AllSeen Alliance." VALUE "MIMEType", "application/x-alljoyn" VALUE "OriginalFilename", "npalljoyn.dll" VALUE "ProductName", "AllJoyn" VALUE "ProductVersion", "15.09.00a" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_PERMISSIONREQ DIALOGEX 0, 0, 196, 105 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Security Warning" FONT 8, "MS Shell Dlg", 0, 0, 0x1 BEGIN LTEXT "The website below wants to use AllJoyn.",IDC_STATIC,12,12,131,8 CTEXT "origin",IDC_ORIGIN,12,30,131,8 LTEXT "Do you want to allow this?",IDC_STATIC,12,48,85,8 CONTROL "Remember my decision for this site",IDC_REMEMBER,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,66,124,8 PUSHBUTTON "Allow",IDYES,84,84,50,14 PUSHBUTTON "Deny",IDNO,138,84,50,14 END alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/windows/FeaturePermissions.cc0000644000175000017500000002140312620747066025054 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../FeaturePermissions.h" #include "../../PluginData.h" #include "resource.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" class RequestPermissionContext { public: qcc::String origin; bool remember; RequestPermissionContext() : remember(false) { } }; static LRESULT CALLBACK DlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: { QCC_DbgTrace(("%s(hwnd=%d,msg=WM_INITDIALOG,wParam=0x%x,lParam=0x%x)", __FUNCTION__, hwnd, wParam, lParam)); /* * Save the context pointer. */ RequestPermissionContext* context = reinterpret_cast(lParam); SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast(context)); /* * Fill in the origin control with the right value. */ int lenW = MultiByteToWideChar(CP_ACP, 0, context->origin.c_str(), -1, NULL, 0); wchar_t* originW = new wchar_t[lenW]; MultiByteToWideChar(CP_ACP, 0, context->origin.c_str(), -1, originW, lenW); if (!SetDlgItemText(hwnd, IDC_ORIGIN, originW)) { QCC_LogError(ER_OS_ERROR, ("SetDlgItemText failed - %d", GetLastError())); } delete[] originW; /* * Center the dialog window. */ HWND parent = GetParent(hwnd); if (NULL == parent) { parent = GetDesktopWindow(); } RECT parentRect; if (!GetWindowRect(parent, &parentRect)) { QCC_LogError(ER_OS_ERROR, ("GetWindowRect(parent) failed - %d", GetLastError())); break; } RECT rect; if (!GetWindowRect(hwnd, &rect)) { QCC_LogError(ER_OS_ERROR, ("GetWindowRect failed - %d", GetLastError())); break; } RECT offset; if (!CopyRect(&offset, &parentRect)) { QCC_LogError(ER_OS_ERROR, ("CopyRect failed - %d", GetLastError())); break; } if (!OffsetRect(&rect, -rect.left, -rect.top)) { QCC_LogError(ER_OS_ERROR, ("OffsetRect failed - %d", GetLastError())); break; } if (!OffsetRect(&offset, -offset.left, -offset.top)) { QCC_LogError(ER_OS_ERROR, ("OffsetRect failed - %d", GetLastError())); break; } if (!OffsetRect(&offset, -rect.right, -rect.bottom)) { QCC_LogError(ER_OS_ERROR, ("OffsetRect failed - %d", GetLastError())); break; } if (!SetWindowPos(hwnd, HWND_TOP, parentRect.left + (offset.right / 2), parentRect.top + (offset.bottom / 2), 0, 0, SWP_NOSIZE)) { QCC_LogError(ER_OS_ERROR, ("SetWindowPos failed - %d", GetLastError())); } break; } case WM_COMMAND: { QCC_DbgTrace(("%s(hwnd=%d,msg=WM_COMMAND,wParam=0x%x,lParam=0x%x)", __FUNCTION__, hwnd, wParam, lParam)); RequestPermissionContext* context = reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_USERDATA)); switch (LOWORD(wParam)) { case IDYES: case IDNO: { if (context) { context->remember = IsDlgButtonChecked(hwnd, IDC_REMEMBER); } else { QCC_LogError(ER_OS_ERROR, ("GetWindowLongPtr returned NULL")); } EndDialog(hwnd, LOWORD(wParam)); break; } case IDCANCEL: EndDialog(hwnd, IDCANCEL); break; } break; } default: return FALSE; } return TRUE; } QStatus RequestPermission(Plugin& plugin, const qcc::String& feature, RequestPermissionListener* listener) { QStatus status = ER_OK; int32_t level; RequestPermissionContext context; NPError npret; HWND hwnd; INT_PTR ret; status = PluginData::PermissionLevel(plugin, feature, level); if (ER_OK != status) { goto exit; } QCC_DbgTrace(("Current permission level is %d", level)); if (DEFAULT_DENIED != level) { listener->RequestPermissionCB(level, false); goto exit; } if (feature != ALLJOYN_FEATURE) { status = ER_FAIL; QCC_LogError(status, ("feature '%s' not supported", feature.c_str())); goto exit; } status = plugin->Origin(context.origin); if (ER_OK != status) { goto exit; } npret = NPN_GetValue(plugin->npp, NPNVnetscapeWindow, &hwnd); if (NPERR_NO_ERROR != npret) { status = ER_FAIL; QCC_LogError(status, ("NPN_GetValue(NPNVnetscapeWindow) failed - %d", npret)); goto exit; } ret = DialogBoxParam(gHinstance, MAKEINTRESOURCE(IDD_PERMISSIONREQ), hwnd, reinterpret_cast(DlgProc), (LPARAM)&context); if (ret <= 0) { status = ER_OS_ERROR; QCC_LogError(ER_OS_ERROR, ("DialogBoxParam failed - %d", GetLastError())); goto exit; } listener->RequestPermissionCB((IDYES == ret) ? USER_ALLOWED : USER_DENIED, context.remember); exit: return status; } QStatus PersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t& level) { level = DEFAULT_DENIED; qcc::String filename = qcc::GetHomeDir() + "/.alljoyn_keystore/" + plugin->ToFilename(origin) + "_permission"; QCC_DbgTrace(("filename=%s", filename.c_str())); qcc::FileSource source(filename); if (source.IsValid()) { source.Lock(true); qcc::String permission; source.GetLine(permission); source.Unlock(); QCC_DbgHLPrintf(("Read permission '%s' from %s", permission.c_str(), filename.c_str())); qcc::String levelString = qcc::Trim(permission); if (levelString == "USER_ALLOWED") { level = USER_ALLOWED; } else if (levelString == "USER_DENIED") { level = USER_DENIED; } else if (levelString == "DEFAULT_ALLOWED") { level = DEFAULT_ALLOWED; } } return ER_OK; } QStatus SetPersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t level) { QStatus status = ER_OK; qcc::String filename = qcc::GetHomeDir() + "/.alljoyn_keystore/" + plugin->ToFilename(origin) + "_permission"; qcc::FileSink sink(filename, qcc::FileSink::PRIVATE); if (sink.IsValid()) { sink.Lock(true); qcc::String permission; /* * Why the '\n' below? FileSink doesn't truncate the existing file, so the line-break * ensures that we don't get any characters leftover from a previous write for a longer * string than the current one. */ switch (level) { case USER_ALLOWED: permission = "USER_ALLOWED\n"; break; case DEFAULT_ALLOWED: permission = "DEFAULT_ALLOWED\n"; break; case DEFAULT_DENIED: permission = "DEFAULT_DENIED\n"; break; case USER_DENIED: permission = "USER_DENIED\n"; break; } size_t bytesWritten; status = sink.PushBytes(permission.c_str(), permission.size(), bytesWritten); if (ER_OK == status) { if (permission.size() == bytesWritten) { QCC_DbgHLPrintf(("Wrote permission '%s' to %s", qcc::Trim(permission).c_str(), filename.c_str())); } else { status = ER_BUS_WRITE_ERROR; QCC_LogError(status, ("Cannot write permission to %s", filename.c_str())); } } sink.Unlock(); } else { status = ER_BUS_WRITE_ERROR; QCC_LogError(status, ("Cannot write permission to %s", filename.c_str())); } return status; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/windows/npalljoyn.def0000644000175000017500000000161312620747066023405 0ustar debiandebian; ; Copyright AllSeen Alliance. All rights reserved. ; ; Permission to use, copy, modify, and/or distribute this software for any ; purpose with or without fee is hereby granted, provided that the above ; copyright notice and this permission notice appear in all copies. ; ; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES ; WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF ; MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ; ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ; WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ; ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF ; OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ; LIBRARY NPALLJOYN EXPORTS NP_GetEntryPoints @1 NP_Initialize @2 NP_Shutdown @3 alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/android/0000755000175000017500000000000012620747066020644 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/android/BusAttachmentHost.cc0000644000175000017500000000203012620747066024546 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../BusAttachmentHost.h" #include #define QCC_MODULE "ALLJOYN_JS" QStatus _BusAttachmentHost::Connect(Plugin& plugin, const char* connectSpec) { return (*busAttachment)->Connect(connectSpec); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/os/android/FeaturePermissions.cc0000644000175000017500000001111612620747066025002 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "../../FeaturePermissions.h" #include "PluginData.h" #include #include #include #include #define QCC_MODULE "ALLJOYN_JS" QStatus RequestPermission(Plugin& plugin, const qcc::String& feature, RequestPermissionListener* listener) { QCC_DbgTrace(("RequestPermission(feature=%s,listener=%p)", feature.c_str(), listener)); QStatus status = ER_OK; int32_t level; qcc::String origin; status = PluginData::PermissionLevel(plugin, feature, level); if (ER_OK != status) { goto exit; } if (DEFAULT_DENIED != level) { listener->RequestPermissionCB(level, false); goto exit; } if (feature != ALLJOYN_FEATURE) { status = ER_FAIL; QCC_LogError(status, ("feature '%s' not supported", feature.c_str())); goto exit; } status = plugin->Origin(origin); if (ER_OK != status) { goto exit; } /* * TODO Implement the request permission dialog. */ listener->RequestPermissionCB(DEFAULT_ALLOWED, false); exit: return status; } QStatus PersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t& level) { /* * TODO Level should be DEFAULT_DENIED in a complete implementation. See TODO above. */ level = DEFAULT_ALLOWED; qcc::String filename = qcc::GetHomeDir() + "/.alljoyn_keystore/" + plugin->ToFilename(origin) + "_permission"; QCC_DbgTrace(("filename=%s", filename.c_str())); qcc::FileSource source(filename); if (source.IsValid()) { source.Lock(true); qcc::String permission; source.GetLine(permission); source.Unlock(); QCC_DbgHLPrintf(("Read permission '%s' from %s", permission.c_str(), filename.c_str())); qcc::String levelString = qcc::Trim(permission); if (levelString == "USER_ALLOWED") { level = USER_ALLOWED; } else if (levelString == "USER_DENIED") { level = USER_DENIED; } else if (levelString == "DEFAULT_ALLOWED") { level = DEFAULT_ALLOWED; } } return ER_OK; } QStatus SetPersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t level) { QStatus status = ER_OK; qcc::String filename = qcc::GetHomeDir() + "/.alljoyn_keystore/" + plugin->ToFilename(origin) + "_permission"; qcc::FileSink sink(filename, qcc::FileSink::PRIVATE); if (sink.IsValid()) { sink.Lock(true); qcc::String permission; /* * Why the '\n' below? FileSink doesn't truncate the existing file, so the line-break * ensures that we don't get any characters leftover from a previous write for a longer * string than the current one. */ switch (level) { case USER_ALLOWED: permission = "USER_ALLOWED\n"; break; case DEFAULT_ALLOWED: permission = "DEFAULT_ALLOWED\n"; break; case DEFAULT_DENIED: permission = "DEFAULT_DENIED\n"; break; case USER_DENIED: permission = "USER_DENIED\n"; break; } size_t bytesWritten; status = sink.PushBytes(permission.c_str(), permission.size(), bytesWritten); if (ER_OK == status) { if (permission.size() == bytesWritten) { QCC_DbgHLPrintf(("Wrote permission '%s' to %s", qcc::Trim(permission).c_str(), filename.c_str())); } else { status = ER_BUS_WRITE_ERROR; QCC_LogError(status, ("Cannot write permission to %s", filename.c_str())); } } sink.Unlock(); } else { status = ER_BUS_WRITE_ERROR; QCC_LogError(status, ("Cannot write permission to %s", filename.c_str())); } return status; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SignalEmitterHost.h0000644000175000017500000000251312620747066022362 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SIGNALEMITTERHOST_H #define _SIGNALEMITTERHOST_H #include "BusObject.h" #include "ScriptableObject.h" #include class _SignalEmitterHost : public ScriptableObject { public: _SignalEmitterHost(Plugin& plugin, BusObject& busObject); virtual ~_SignalEmitterHost(); private: BusObject busObject; bool emitSignal(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_SignalEmitterHost> SignalEmitterHost; #endif // _SIGNALEMITTERHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusObjectNative.cc0000644000175000017500000001674512620747066022156 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "BusObjectNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" BusObjectNative::BusObjectNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } BusObjectNative::~BusObjectNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void BusObjectNative::onRegistered() { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onRegistered = NPN_GetStringIdentifier("onRegistered"); if (NPN_HasMethod(plugin->npp, objectValue, onRegistered)) { NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onRegistered, 0, 0, &result); NPN_ReleaseVariantValue(&result); } } void BusObjectNative::onUnregistered() { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onUnregistered = NPN_GetStringIdentifier("onUnregistered"); if (NPN_HasMethod(plugin->npp, objectValue, onUnregistered)) { NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onUnregistered, 0, 0, &result); NPN_ReleaseVariantValue(&result); } } QStatus BusObjectNative::get(const ajn::InterfaceDescription* iface, const ajn::InterfaceDescription::Property* prop, ajn::MsgArg& val) { QCC_DbgTrace(("%s", __FUNCTION__)); NPVariant interface = NPVARIANT_VOID; NPVariant getter = NPVARIANT_VOID; NPVariant value = NPVARIANT_VOID; QStatus status = ER_OK; bool typeError = false; NPVariant nparg; if (!NPN_GetProperty(plugin->npp, objectValue, NPN_GetStringIdentifier(iface->GetName()), &interface) || !NPVARIANT_IS_OBJECT(interface)) { status = ER_BUS_OBJECT_NO_SUCH_INTERFACE; goto exit; } STRINGN_TO_NPVARIANT(prop->name.c_str(), (uint32_t)prop->name.size(), nparg); if (!NPN_Invoke(plugin->npp, NPVARIANT_TO_OBJECT(interface), NPN_GetStringIdentifier("__lookupGetter__"), &nparg, 1, &getter) || !NPVARIANT_IS_OBJECT(getter)) { status = ER_FAIL; goto exit; } if (!NPN_InvokeDefault(plugin->npp, NPVARIANT_TO_OBJECT(getter), 0, 0, &value)) { status = ER_FAIL; } ToAny(plugin, value, prop->signature, val, typeError); if (typeError) { status = ER_FAIL; } exit: NPN_ReleaseVariantValue(&value); NPN_ReleaseVariantValue(&getter); NPN_ReleaseVariantValue(&interface); return status; } QStatus BusObjectNative::set(const ajn::InterfaceDescription* iface, const ajn::InterfaceDescription::Property* prop, const ajn::MsgArg& val) { QCC_DbgTrace(("%s", __FUNCTION__)); NPVariant interface = NPVARIANT_VOID; NPVariant nparg; NPVariant setter = NPVARIANT_VOID; NPVariant value = NPVARIANT_VOID; NPVariant ignore = NPVARIANT_VOID; QStatus status = ER_OK; if (!NPN_GetProperty(plugin->npp, objectValue, NPN_GetStringIdentifier(iface->GetName()), &interface) || !NPVARIANT_IS_OBJECT(interface)) { status = ER_BUS_OBJECT_NO_SUCH_INTERFACE; goto exit; } STRINGN_TO_NPVARIANT(prop->name.c_str(), (uint32_t)prop->name.size(), nparg); if (!NPN_Invoke(plugin->npp, NPVARIANT_TO_OBJECT(interface), NPN_GetStringIdentifier("__lookupSetter__"), &nparg, 1, &setter) || !NPVARIANT_IS_OBJECT(setter)) { status = ER_FAIL; goto exit; } ToAny(plugin, val, value, status); if (ER_OK != status) { goto exit; } if (!NPN_InvokeDefault(plugin->npp, NPVARIANT_TO_OBJECT(setter), &value, 1, &ignore)) { status = ER_FAIL; } exit: NPN_ReleaseVariantValue(&ignore); NPN_ReleaseVariantValue(&value); NPN_ReleaseVariantValue(&setter); NPN_ReleaseVariantValue(&interface); return status; } QStatus BusObjectNative::toXML(bool deep, size_t indent, qcc::String& xml) { QCC_DbgTrace(("%s(deep=%d,indent=%d)", __FUNCTION__, deep, indent)); QStatus status = ER_NOT_IMPLEMENTED; NPIdentifier toXML = NPN_GetStringIdentifier("toXML"); if (NPN_HasMethod(plugin->npp, objectValue, toXML)) { NPVariant npargs[2]; ToBoolean(plugin, deep, npargs[0]); ToUnsignedLong(plugin, indent, npargs[1]); NPVariant result = NPVARIANT_VOID; if (NPN_Invoke(plugin->npp, objectValue, toXML, npargs, 2, &result) && NPVARIANT_IS_STRING(result)) { bool typeError; xml = ToDOMString(plugin, result, typeError); if (!typeError) { status = ER_OK; } } NPN_ReleaseVariantValue(&result); } return status; } void BusObjectNative::onMessage(const char* interfaceName, const char* methodName, MessageReplyHost& message, const ajn::MsgArg* args, size_t numArgs) { QCC_DbgTrace(("%s(args=%p,numArgs=%d)", __FUNCTION__, args, numArgs)); #if !defined(NDEBUG) qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); #endif NPVariant interface = NPVARIANT_VOID; NPVariant method = NPVARIANT_VOID; NPVariant result = NPVARIANT_VOID; QStatus status = ER_OK; uint32_t npargCount = 0; NPVariant* npargs = NULL; size_t i; npargCount = 1 + numArgs; npargs = new NPVariant[npargCount]; ToHostObject(plugin, message, npargs[0]); for (i = 0; (ER_OK == status) && (i < numArgs); ++i) { ToAny(plugin, args[i], npargs[1 + i], status); } if (ER_OK != status) { npargCount = 1 + i; goto exit; } if (!NPN_GetProperty(plugin->npp, objectValue, NPN_GetStringIdentifier(interfaceName), &interface) || !NPVARIANT_IS_OBJECT(interface)) { status = ER_BUS_OBJECT_NO_SUCH_INTERFACE; goto exit; } if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(interface), NPN_GetStringIdentifier(methodName), &method) || !NPVARIANT_IS_OBJECT(method)) { status = ER_BUS_OBJECT_NO_SUCH_MEMBER; goto exit; } if (!NPN_InvokeDefault(plugin->npp, NPVARIANT_TO_OBJECT(method), npargs, npargCount, &result)) { status = ER_FAIL; QCC_LogError(status, ("NPN_InvokeDefault failed")); } exit: if ((ER_OK != status) && NPN_HasMethod(plugin->npp, NPVARIANT_TO_OBJECT(npargs[0]), NPN_GetStringIdentifier("replyError"))) { NPVariant args[2]; INT32_TO_NPVARIANT(status, args[0]); VOID_TO_NPVARIANT(args[1]); NPVariant ignore = NPVARIANT_VOID; NPN_Invoke(plugin->npp, NPVARIANT_TO_OBJECT(npargs[0]), NPN_GetStringIdentifier("replyError"), args, 2, &ignore); NPN_ReleaseVariantValue(&ignore); } for (uint32_t j = 0; j < npargCount; ++j) { NPN_ReleaseVariantValue(&npargs[j]); } delete[] npargs; NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&method); NPN_ReleaseVariantValue(&interface); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AboutObjHost.h0000644000175000017500000000253312620747066021322 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _ABOUTOBJHOST_H #define _ABOUTOBJHOST_H #include "BusAttachment.h" #include "ScriptableObject.h" #include "AboutObj.h" #include class _AboutObjHost : public ScriptableObject { public: _AboutObjHost(Plugin& plugin, BusAttachment& busAttachment); virtual ~_AboutObjHost(); private: BusAttachment busAttachment; AboutObj aboutObj; ajn::AboutData* aboutData; bool announce(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_AboutObjHost> AboutObjHost; #endif alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionJoinedListenerNative.h0000644000175000017500000000243612620747066024412 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONJOINEDLISTENERNATIVE_H #define _SESSIONJOINEDLISTENERNATIVE_H #include "NativeObject.h" #include #include class SessionJoinedListenerNative : public NativeObject { public: SessionJoinedListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~SessionJoinedListenerNative(); void onJoined(ajn::SessionPort port, ajn::SessionId id, const qcc::String& joiner); }; #endif // _SESSIONJOINEDLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/HttpListenerNative.h0000644000175000017500000000226612620747066022556 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _HTTPLISTENERNATIVE_H #define _HTTPLISTENERNATIVE_H #include "HttpRequestHost.h" #include "NativeObject.h" #include class HttpListenerNative : public NativeObject { public: HttpListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~HttpListenerNative(); void onRequest(HttpRequestHost& request); }; #endif // _HTTPLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/ProxyBusObjectHost.h0000644000175000017500000000461112620747066022536 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _PROXYBUSOBJECTHOST_H #define _PROXYBUSOBJECTHOST_H #include "BusAttachment.h" #include "ProxyBusObject.h" #include "ScriptableObject.h" #include class _ProxyBusObjectHostImpl; class _ProxyBusObjectHost : public ScriptableObject { public: _ProxyBusObjectHost(Plugin& plugin, BusAttachment& busAttachment, const char* serviceName, const char* path, ajn::SessionId sessionId); _ProxyBusObjectHost(Plugin& plugin, BusAttachment& busAttachment, ajn::ProxyBusObject* proxyBusObject); virtual ~_ProxyBusObjectHost(); private: BusAttachment busAttachment; ProxyBusObject proxyBusObject; _ProxyBusObjectHostImpl* impl; /* Hide declaration of ProxyChildrenHost to get around recursive include. */ void Initialize(); bool getPath(NPVariant* result); bool getServiceName(NPVariant* result); bool getSessionId(NPVariant* result); bool getSecure(NPVariant* result); bool getChildren(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getInterface(const NPVariant* args, uint32_t argCount, NPVariant* result); bool getInterfaces(const NPVariant* args, uint32_t argCount, NPVariant* result); bool introspect(const NPVariant* args, uint32_t argCount, NPVariant* result); bool methodCall(const NPVariant* args, uint32_t argCount, NPVariant* result); bool parseXML(const NPVariant* args, uint32_t argCount, NPVariant* result); bool secureConnection(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_ProxyBusObjectHost> ProxyBusObjectHost; #endif // _PROXYBUSOBJECTHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/NativeObject.cc0000644000175000017500000000403712620747066021473 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "NativeObject.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" NativeObject::NativeObject(Plugin& plugin, NPObject* objectValue) : plugin(plugin), objectValue(NPN_RetainObject(objectValue)) { QCC_DbgTrace(("%s(objectValue=%p)", __FUNCTION__, objectValue)); plugin->nativeObjects[this] = objectValue; } NativeObject::NativeObject(Plugin& plugin) : plugin(plugin), objectValue(NULL) { QCC_DbgTrace(("%s", __FUNCTION__)); NPVariant variant = NPVARIANT_VOID; if (NewObject(plugin, variant)) { objectValue = NPVARIANT_TO_OBJECT(variant); plugin->nativeObjects[this] = objectValue; } else { NPN_ReleaseVariantValue(&variant); } } NativeObject::~NativeObject() { QCC_DbgTrace(("%s", __FUNCTION__)); plugin->nativeObjects.erase(this); Invalidate(); } void NativeObject::Invalidate() { QCC_DbgTrace(("%s", __FUNCTION__)); if (objectValue) { NPN_ReleaseObject(objectValue); objectValue = NULL; } } bool NativeObject::operator==(const NativeObject& that) const { NPVariant a, b; OBJECT_TO_NPVARIANT(objectValue, a); OBJECT_TO_NPVARIANT(that.objectValue, b); return plugin->StrictEquals(a, b); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SocketFdInterface.h0000644000175000017500000000273712620747066022310 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SOCKETFDINTERFACE_H #define _SOCKETFDINTERFACE_H #include "HttpServer.h" #include "ScriptableObject.h" #include class _SocketFdInterface : public ScriptableObject { public: _SocketFdInterface(Plugin& plugin); virtual ~_SocketFdInterface(); virtual bool Construct(const NPVariant* args, uint32_t argCount, NPVariant* result); private: HttpServer httpServer; bool createObjectURL(const NPVariant* args, uint32_t argCount, NPVariant* result); bool revokeObjectURL(const NPVariant* args, uint32_t argCount, NPVariant* result); }; typedef qcc::ManagedObj<_SocketFdInterface> SocketFdInterface; #endif // _SOCKETFDINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionLostReasonInterface.h0000644000175000017500000000253112620747066024233 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONLOSTREASONINTERFACE_H #define _SESSIONLOSTREASONINTERFACE_H #include "ScriptableObject.h" #include class _SessionLostReasonInterface : public ScriptableObject { public: static std::map& Constants(); _SessionLostReasonInterface(Plugin& plugin); virtual ~_SessionLostReasonInterface(); private: static std::map constants; }; typedef qcc::ManagedObj<_SessionLostReasonInterface> SessionLostReasonInterface; #endif // _SESSIONLOSTREASONINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/CredentialsHost.cc0000644000175000017500000001251212620747066022206 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "CredentialsHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" _CredentialsHost::_CredentialsHost(Plugin& plugin, ajn::AuthListener::Credentials& credentials) : ScriptableObject(plugin, _CredentialsInterface::Constants()), credentials(credentials) { QCC_DbgTrace(("%s", __FUNCTION__)); ATTRIBUTE("password", &_CredentialsHost::getPassword, &_CredentialsHost::setPassword); ATTRIBUTE("userName", &_CredentialsHost::getUserName, &_CredentialsHost::setUserName); ATTRIBUTE("certChain", &_CredentialsHost::getCertChain, &_CredentialsHost::setCertChain); ATTRIBUTE("privateKey", &_CredentialsHost::getPrivateKey, &_CredentialsHost::setPrivateKey); ATTRIBUTE("logonEntry", &_CredentialsHost::getLogonEntry, &_CredentialsHost::setLogonEntry); ATTRIBUTE("expiration", &_CredentialsHost::getExpiration, &_CredentialsHost::setExpiration); } _CredentialsHost::~_CredentialsHost() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool _CredentialsHost::getPassword(NPVariant* result) { if (credentials.IsSet(ajn::AuthListener::CRED_PASSWORD)) { ToDOMString(plugin, credentials.GetPassword(), *result); } else { VOID_TO_NPVARIANT(*result); } return true; } bool _CredentialsHost::getUserName(NPVariant* result) { if (credentials.IsSet(ajn::AuthListener::CRED_USER_NAME)) { ToDOMString(plugin, credentials.GetUserName(), *result); } else { VOID_TO_NPVARIANT(*result); } return true; } bool _CredentialsHost::getCertChain(NPVariant* result) { if (credentials.IsSet(ajn::AuthListener::CRED_CERT_CHAIN)) { ToDOMString(plugin, credentials.GetCertChain(), *result); } else { VOID_TO_NPVARIANT(*result); } return true; } bool _CredentialsHost::getPrivateKey(NPVariant* result) { if (credentials.IsSet(ajn::AuthListener::CRED_PRIVATE_KEY)) { ToDOMString(plugin, credentials.GetPrivateKey(), *result); } else { VOID_TO_NPVARIANT(*result); } return true; } bool _CredentialsHost::getLogonEntry(NPVariant* result) { if (credentials.IsSet(ajn::AuthListener::CRED_LOGON_ENTRY)) { ToDOMString(plugin, credentials.GetLogonEntry(), *result); } else { VOID_TO_NPVARIANT(*result); } return true; } bool _CredentialsHost::getExpiration(NPVariant* result) { uint32_t expiration = credentials.GetExpiration(); if (0xFFFFFFFF != expiration) { ToUnsignedLong(plugin, expiration, *result); } else { VOID_TO_NPVARIANT(*result); } return true; } bool _CredentialsHost::setPassword(const NPVariant* value) { bool typeError; qcc::String password = ToDOMString(plugin, *value, typeError); if (!typeError) { credentials.SetPassword(password); return true; } else { plugin->RaiseTypeError("value is not a string"); return false; } } bool _CredentialsHost::setUserName(const NPVariant* value) { bool typeError; qcc::String userName = ToDOMString(plugin, *value, typeError); if (!typeError) { credentials.SetUserName(userName); return true; } else { plugin->RaiseTypeError("value is not a string"); return false; } } bool _CredentialsHost::setCertChain(const NPVariant* value) { bool typeError; qcc::String certChain = ToDOMString(plugin, *value, typeError); if (!typeError) { credentials.SetCertChain(certChain); return true; } else { plugin->RaiseTypeError("value is not a string"); return false; } } bool _CredentialsHost::setPrivateKey(const NPVariant* value) { bool typeError; qcc::String privateKey = ToDOMString(plugin, *value, typeError); if (!typeError) { credentials.SetPrivateKey(privateKey); return true; } else { plugin->RaiseTypeError("value is not a string"); return false; } } bool _CredentialsHost::setLogonEntry(const NPVariant* value) { bool typeError; qcc::String logonEntry = ToDOMString(plugin, *value, typeError); if (!typeError) { credentials.SetLogonEntry(logonEntry); return true; } else { plugin->RaiseTypeError("value is not a string"); return false; } } bool _CredentialsHost::setExpiration(const NPVariant* value) { bool typeError; uint32_t expiration = ToUnsignedLong(plugin, *value, typeError); if (!typeError) { credentials.SetExpiration(expiration); return true; } else { plugin->RaiseTypeError("value is not a number"); return false; } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionOptsHost.h0000644000175000017500000000263312620747066022107 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONOPTSHOST_H #define _SESSIONOPTSHOST_H #include "ScriptableObject.h" #include #include class _SessionOptsHost : public ScriptableObject { public: _SessionOptsHost(Plugin& plugin, const ajn::SessionOpts& opts); virtual ~_SessionOptsHost(); private: const ajn::SessionOpts opts; bool getTraffic(NPVariant* result); bool getIsMultipoint(NPVariant* result); bool getProximity(NPVariant* result); bool getTransports(NPVariant* result); }; typedef qcc::ManagedObj<_SessionOptsHost> SessionOptsHost; #endif // _SESSIONOPTSHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionMemberAddedListenerNative.cc0000644000175000017500000000326012620747066025465 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SessionMemberAddedListenerNative.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" SessionMemberAddedListenerNative::SessionMemberAddedListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } SessionMemberAddedListenerNative::~SessionMemberAddedListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void SessionMemberAddedListenerNative::onMemberAdded(ajn::SessionId id, const qcc::String& uniqueName) { QCC_DbgTrace(("%s(id=%u,uniqueName=%s)", __FUNCTION__, id, uniqueName.c_str())); NPVariant npargs[2]; ToUnsignedLong(plugin, id, npargs[0]); ToDOMString(plugin, uniqueName, npargs[1]); NPVariant result = NPVARIANT_VOID; NPN_InvokeDefault(plugin->npp, objectValue, npargs, 2, &result); NPN_ReleaseVariantValue(&result); } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/BusListenerNative.cc0000644000175000017500000001514312620747066022524 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "BusListenerNative.h" #include "BusAttachmentHost.h" #include "TypeMapping.h" #include #define QCC_MODULE "ALLJOYN_JS" BusListenerNative::BusListenerNative(Plugin& plugin, NPObject* objectValue) : NativeObject(plugin, objectValue) { QCC_DbgTrace(("%s", __FUNCTION__)); } BusListenerNative::~BusListenerNative() { QCC_DbgTrace(("%s", __FUNCTION__)); } void BusListenerNative::onRegistered(BusAttachmentHost& busAttachment) { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onRegistered = NPN_GetStringIdentifier("onRegistered"); if (NPN_HasMethod(plugin->npp, objectValue, onRegistered)) { NPVariant npargs[1]; ToHostObject(plugin, busAttachment, npargs[0]); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onRegistered, npargs, 1, &result); NPN_ReleaseVariantValue(&npargs[0]); NPN_ReleaseVariantValue(&result); } } void BusListenerNative::onUnregistered() { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onUnregistered = NPN_GetStringIdentifier("onUnregistered"); if (NPN_HasMethod(plugin->npp, objectValue, onUnregistered)) { NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onUnregistered, 0, 0, &result); NPN_ReleaseVariantValue(&result); } } void BusListenerNative::onFoundAdvertisedName(const qcc::String& name, ajn::TransportMask transport, const qcc::String& namePrefix) { QCC_DbgTrace(("%s(name=%s,transport=0x%x,namePrefix=%s)", __FUNCTION__, name.c_str(), transport, namePrefix.c_str())); NPIdentifier onFoundAdvertisedName = NPN_GetStringIdentifier("onFoundAdvertisedName"); if (NPN_HasMethod(plugin->npp, objectValue, onFoundAdvertisedName)) { NPVariant npargs[3]; ToDOMString(plugin, name, npargs[0]); ToUnsignedShort(plugin, transport, npargs[1]); ToDOMString(plugin, namePrefix, npargs[2]); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onFoundAdvertisedName, npargs, 3, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); NPN_ReleaseVariantValue(&npargs[0]); } } void BusListenerNative::onLostAdvertisedName(const qcc::String& name, ajn::TransportMask transport, const qcc::String& namePrefix) { QCC_DbgTrace(("%s(name=%s,transport=0x%x,namePrefix=%s)", __FUNCTION__, name.c_str(), transport, namePrefix.c_str())); NPIdentifier onLostAdvertisedName = NPN_GetStringIdentifier("onLostAdvertisedName"); if (NPN_HasMethod(plugin->npp, objectValue, onLostAdvertisedName)) { NPVariant npargs[3]; ToDOMString(plugin, name, npargs[0]); ToUnsignedShort(plugin, transport, npargs[1]); ToDOMString(plugin, namePrefix, npargs[2]); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onLostAdvertisedName, npargs, 3, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); NPN_ReleaseVariantValue(&npargs[0]); } } void BusListenerNative::onNameOwnerChanged(const qcc::String& busName, const qcc::String& previousOwner, const qcc::String& newOwner) { QCC_DbgTrace(("%s(busName=%s,previousOwner=%s,newOwner=%s)", __FUNCTION__, busName.c_str(), previousOwner.c_str(), newOwner.c_str())); NPIdentifier onNameOwnerChanged = NPN_GetStringIdentifier("onNameOwnerChanged"); if (NPN_HasMethod(plugin->npp, objectValue, onNameOwnerChanged)) { NPVariant npargs[3]; ToDOMString(plugin, busName, npargs[0]); ToDOMString(plugin, previousOwner, npargs[1], TreatEmptyStringAsNull); ToDOMString(plugin, newOwner, npargs[2], TreatEmptyStringAsNull); NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onNameOwnerChanged, npargs, 3, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[2]); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&npargs[0]); } } void BusListenerNative::onPropertyChanged(const qcc::String& propName, const ajn::MsgArg* propValue) { QCC_DbgTrace(("%s(propName=%s,propValue=%s)", __FUNCTION__, propName.c_str(), propValue ? propValue->ToString().c_str() : "")); NPIdentifier onPropertyChanged = NPN_GetStringIdentifier("onPropertyChanged"); if (NPN_HasMethod(plugin->npp, objectValue, onPropertyChanged)) { NPVariant npargs[2]; ToDOMString(plugin, propName, npargs[0]); if (propValue != NULL) { QStatus status = ER_OK; ToAny(plugin, *propValue, npargs[1], status); assert(status == ER_OK); } else { // null string indicates no propValue ToDOMString(plugin, NULL, 0, npargs[1], TreatEmptyStringAsNull); } NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onPropertyChanged, npargs, 2, &result); NPN_ReleaseVariantValue(&result); NPN_ReleaseVariantValue(&npargs[1]); NPN_ReleaseVariantValue(&npargs[0]); } } void BusListenerNative::onStopping() { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onStopping = NPN_GetStringIdentifier("onStopping"); if (NPN_HasMethod(plugin->npp, objectValue, onStopping)) { NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onStopping, 0, 0, &result); NPN_ReleaseVariantValue(&result); } } void BusListenerNative::onDisconnected() { QCC_DbgTrace(("%s", __FUNCTION__)); NPIdentifier onDisconnected = NPN_GetStringIdentifier("onDisconnected"); if (NPN_HasMethod(plugin->npp, objectValue, onDisconnected)) { NPVariant result = NPVARIANT_VOID; NPN_Invoke(plugin->npp, objectValue, onDisconnected, 0, 0, &result); NPN_ReleaseVariantValue(&result); } } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionMemberAddedListenerNative.h0000644000175000017500000000245612620747066025335 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONMEMBERADDEDLISTENERNATIVE_H #define _SESSIONMEMBERADDEDLISTENERNATIVE_H #include "NativeObject.h" #include #include class SessionMemberAddedListenerNative : public NativeObject { public: SessionMemberAddedListenerNative(Plugin& plugin, NPObject* objectValue); virtual ~SessionMemberAddedListenerNative(); void onMemberAdded(ajn::SessionId id, const qcc::String& uniqueName); }; #endif // _SESSIONMEMBERADDEDLISTENERNATIVE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/FeaturePermissions.h0000644000175000017500000000345512620747066022612 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _FEATUREPERMISSIONS_H #define _FEATUREPERMISSIONS_H #include "Plugin.h" #include /* * Feature identifiers. */ #define ALLJOYN_FEATURE "org.alljoyn.bus" /* * Permission levels. */ #define USER_ALLOWED 2 #define DEFAULT_ALLOWED 1 #define DEFAULT_DENIED -1 #define USER_DENIED -2 class RequestPermissionListener { public: virtual ~RequestPermissionListener() { } virtual void RequestPermissionCB(int32_t level, bool remember) = 0; }; /** * @param listener called when the user allows or denies permission. If this function returns ER_OK then * the listener must remain valid until its RequestPermissionCB() is called. */ QStatus RequestPermission(Plugin& plugin, const qcc::String& feature, RequestPermissionListener* listener); QStatus PersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t& level); QStatus SetPersistentPermissionLevel(Plugin& plugin, const qcc::String& origin, int32_t level); #endif // _FEATUREPERMISSIONS_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SConscript0000644000175000017500000000355012620747066020620 0ustar debiandebian# Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Import('env') libenv = env.Clone() # Plugin library sources srcs = libenv.Glob('*.cc') if '' != libenv.subst('$GECKO_BASE'): libenv.Append(CPPPATH = [libenv.Dir('.').srcnode(), libenv.Dir('npapi').srcnode(), libenv.subst('$GECKO_BASE/include')]) srcs.append(libenv.Glob('npapi/*.cc')) else: libenv.Append(CPPPATH = [libenv.Dir('.').srcnode(), libenv.Dir('cordova').srcnode()]) srcs.append(libenv.Glob('cordova/*.cc')) srcs.append(libenv.Glob('cordova/${OS_CONF}/*.cc')) srcs.append(libenv.Glob('os/${OS_CONF}/*.cc')) objs = libenv.SharedObject(srcs) if libenv['OS_CONF'] == 'windows': objs.append(['os/${OS_CONF}/npalljoyn.def', libenv.RES('os/${OS_CONF}/npalljoyn.rc')]) if libenv['LIBTYPE'] == 'both': # Need to replace the shared alljoyn library with the static one for linking the plugin. libs = libenv['LIBS'] libs[libs.index('alljoyn')] = libenv.File('$DISTDIR/cpp/lib/${LIBPREFIX}alljoyn${LIBSUFFIX}') libenv.Replace(LIBS = libs) # Plugin library npalljoyn = libenv.SharedLibrary('npalljoyn', objs) shlibs = ['npalljoyn'] Return(shlibs) alljoyn-15.09a+dfsg.1/alljoyn_js/jni/CredentialsHost.h0000644000175000017500000000350612620747066022053 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _CREDENTIALSHOST_H #define _CREDENTIALSHOST_H #include "BusAttachment.h" #include "ScriptableObject.h" #include class _CredentialsHost : public ScriptableObject { public: _CredentialsHost(Plugin& plugin, ajn::AuthListener::Credentials& credentials); virtual ~_CredentialsHost(); protected: ajn::AuthListener::Credentials& credentials; bool getPassword(NPVariant* npresult); bool setPassword(const NPVariant* npvalue); bool getUserName(NPVariant* npresult); bool setUserName(const NPVariant* npvalue); bool getCertChain(NPVariant* npresult); bool setCertChain(const NPVariant* npvalue); bool getPrivateKey(NPVariant* npresult); bool setPrivateKey(const NPVariant* npvalue); bool getLogonEntry(NPVariant* npresult); bool setLogonEntry(const NPVariant* npvalue); bool getExpiration(NPVariant* npresult); bool setExpiration(const NPVariant* npvalue); }; typedef qcc::ManagedObj<_CredentialsHost> CredentialsHost; #endif // _CREDENTIALSHOST_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/TypeMapping.h0000644000175000017500000001227212620747066021215 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _TYPEMAPPING_H #define _TYPEMAPPING_H #include "HostObject.h" #include "npn.h" #include #include #include bool NewObject(Plugin& plugin, NPVariant& variant); bool NewArray(Plugin& plugin, NPVariant& variant); void ToAny(Plugin& plugin, const NPVariant& value, const qcc::String signature, ajn::MsgArg& arg, bool& typeError); void ToAny(Plugin& plugin, const ajn::MsgArg& value, NPVariant& variant, QStatus& status); bool ToBoolean(Plugin& plugin, const NPVariant& value, bool& typeError); void ToBoolean(Plugin& plugin, bool value, NPVariant& variant); uint8_t ToOctet(Plugin& plugin, const NPVariant& value, bool& typeError); void ToOctet(Plugin& plugin, uint8_t value, NPVariant& variant); int16_t ToShort(Plugin& plugin, const NPVariant& value, bool& typeError); void ToShort(Plugin& plugin, int16_t value, NPVariant& variant); uint16_t ToUnsignedShort(Plugin& plugin, const NPVariant& value, bool& typeError); void ToUnsignedShort(Plugin& plugin, uint16_t value, NPVariant& variant); int32_t ToLong(Plugin& plugin, const NPVariant& value, bool& typeError); void ToLong(Plugin& plugin, int32_t value, NPVariant& variant); uint32_t ToUnsignedLong(Plugin& plugin, const NPVariant& value, bool& typeError); void ToUnsignedLong(Plugin& plugin, uint32_t value, NPVariant& variant); int64_t ToLongLong(Plugin& plugin, const NPVariant& value, bool& typeError); void ToLongLong(Plugin& plugin, int64_t value, NPVariant& variant); uint64_t ToUnsignedLongLong(Plugin& plugin, const NPVariant& value, bool& typeError); void ToUnsignedLongLong(Plugin& plugin, uint64_t value, NPVariant& variant); double ToDouble(Plugin& plugin, const NPVariant& value, bool& typeError); void ToDouble(Plugin& plugin, double value, NPVariant& variant); qcc::String ToDOMString(Plugin& plugin, const NPVariant& value, bool& typeError, bool treatNullAsEmptyString = false, bool treatUndefinedAsEmptyString = false); typedef enum { TreatEmptyStringAsEmptyString, TreatEmptyStringAsNull, TreatEmptyStringAsUndefined, } TreatEmptyStringAs; /** * @param variant the string. It must be released by the caller. */ void ToDOMString(Plugin& plugin, qcc::String value, NPVariant& variant, TreatEmptyStringAs treatEmptyStringAs = TreatEmptyStringAsEmptyString); /** * @param variant the string. It must be released by the caller. */ void ToDOMString(Plugin& plugin, const char* str, uint32_t len, NPVariant& variant, TreatEmptyStringAs treatEmptyStringAs = TreatEmptyStringAsEmptyString); /** * @return a NativeObject. The native object must be released by the caller with delete. Note that * the return value may be 0 if the variant is undefined or null. */ template T* ToNativeObject(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; if (NPVARIANT_IS_VOID(value) || NPVARIANT_IS_NULL(value)) { return 0; } else if (!NPVARIANT_IS_OBJECT(value)) { typeError = true; return 0; } else { return new T(plugin, NPVARIANT_TO_OBJECT(value)); } } /** * @param value a NativeObject. * @param variant the native object. It must be released by the caller. */ template void ToNativeObject(Plugin& plugin, T* value, NPVariant& variant) { QCC_UNUSED(plugin); if (value && value->objectValue) { NPN_RetainObject(value->objectValue); OBJECT_TO_NPVARIANT(value->objectValue, variant); } else { NULL_TO_NPVARIANT(variant); } } template void ToHostObject(Plugin& plugin, T& value, NPVariant& variant) { OBJECT_TO_NPVARIANT(HostObject::GetInstance(plugin, value), variant); } /* * This is a bit of a hack to get the impl pointer out of a native object pointer. Ideally it would * return a reference, but there's no such thing as a null/uninitialized reference. */ template T* ToHostObject(Plugin& plugin, const NPVariant& value, bool& typeError) { typeError = false; if (NPVARIANT_IS_VOID(value) || NPVARIANT_IS_NULL(value)) { return 0; } if (!NPVARIANT_IS_OBJECT(value)) { typeError = true; return 0; } NPObject* npobj = NPVARIANT_TO_OBJECT(value); if (&HostObject::Class != npobj->_class) { typeError = true; return 0; } return HostObject::GetImpl(plugin, npobj); } #endif // _TYPEMAPPING_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/ProxyBusObjectHost.cc0000644000175000017500000006151712620747066022704 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "ProxyBusObjectHost.h" //#include "BusUtil.h" #include "CallbackNative.h" #include "InterfaceDescriptionNative.h" #include "SignatureUtils.h" #include "TypeMapping.h" #include #include #define QCC_MODULE "ALLJOYN_JS" class IntrospectRemoteObjectAsyncCB : public ajn::ProxyBusObject::Listener { public: class _Env { public: Plugin plugin; BusAttachment busAttachment; ProxyBusObject proxyBusObject; CallbackNative* callbackNative; _Env(Plugin& plugin, BusAttachment& busAttachment, ProxyBusObject& proxyBusObject, CallbackNative* callbackNative) : plugin(plugin), busAttachment(busAttachment), proxyBusObject(proxyBusObject), callbackNative(callbackNative) { } ~_Env() { delete callbackNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; IntrospectRemoteObjectAsyncCB(Plugin& plugin, BusAttachment& busAttachment, ProxyBusObject& proxyBusObject, CallbackNative* callbackNative) : env(plugin, busAttachment, proxyBusObject, callbackNative) { } virtual ~IntrospectRemoteObjectAsyncCB() { } class IntrospectCBContext : public PluginData::CallbackContext { public: Env env; QStatus status; IntrospectCBContext(Env& env, QStatus status) : env(env), status(status) { } }; virtual void IntrospectCB(QStatus status, ajn::ProxyBusObject*, void*) { PluginData::Callback callback(env->plugin, _IntrospectCB); callback->context = new IntrospectCBContext(env, status); delete this; PluginData::DispatchCallback(callback); } static void _IntrospectCB(PluginData::CallbackContext* ctx) { IntrospectCBContext* context = static_cast(ctx); if (ER_OK == context->status) { context->env->callbackNative->onCallback(context->status); } else { BusErrorHost busError(context->env->plugin, context->status); context->env->callbackNative->onCallback(busError); } } }; class ReplyReceiver : public ajn::ProxyBusObject::Listener, public ajn::MessageReceiver { public: class _Env { public: ReplyReceiver* thiz; Plugin plugin; BusAttachment busAttachment; ProxyBusObject proxyBusObject; qcc::String interfaceName; qcc::String methodName; CallbackNative* callbackNative; NPVariant* npargs; uint32_t npargCount; QStatus status; qcc::String errorMessage; _Env(ReplyReceiver* thiz, Plugin& plugin, BusAttachment& busAttachment, ProxyBusObject& proxyBusObject, qcc::String& interfaceName, qcc::String& methodName, CallbackNative* callbackNative, const NPVariant* npargs, uint32_t npargCount) : thiz(thiz), plugin(plugin), busAttachment(busAttachment), proxyBusObject(proxyBusObject), interfaceName(interfaceName), methodName(methodName), callbackNative(callbackNative) { this->npargCount = npargCount; this->npargs = new NPVariant[this->npargCount]; for (uint32_t i = 0; i < this->npargCount; ++i) { NPN_RetainVariantValue(&npargs[i], &this->npargs[i]); } } ~_Env() { for (uint32_t i = 0; i < npargCount; ++i) { NPN_ReleaseVariantValue(&npargs[i]); } delete[] npargs; delete callbackNative; } }; typedef qcc::ManagedObj<_Env> Env; Env env; ReplyReceiver(Plugin& plugin, BusAttachment& busAttachment, ProxyBusObject& proxyBusObject, qcc::String& interfaceName, qcc::String& methodName, CallbackNative* callbackNative, const NPVariant* npargs, uint32_t npargCount) : env(this, plugin, busAttachment, proxyBusObject, interfaceName, methodName, callbackNative, npargs, npargCount) { } virtual ~ReplyReceiver() { } class IntrospectCBContext : public PluginData::CallbackContext { public: Env env; QStatus status; IntrospectCBContext(Env& env, QStatus status) : env(env), status(status) { } virtual ~IntrospectCBContext() { if (ER_OK != env->status) { ajn::Message message(*env->busAttachment); env->thiz->ReplyHandler(message, 0); } } }; virtual void IntrospectCB(QStatus status, ajn::ProxyBusObject* obj, void* context) { QCC_UNUSED(obj); QCC_UNUSED(context); PluginData::Callback callback(env->plugin, _IntrospectCB); callback->context = new IntrospectCBContext(env, status); PluginData::DispatchCallback(callback); } static void _IntrospectCB(PluginData::CallbackContext* ctx) { IntrospectCBContext* context = static_cast(ctx); Env& env = context->env; if (ER_OK != context->status) { QCC_LogError(context->status, ("IntrospectRemoteObjectAsync failed")); } const ajn::InterfaceDescription* iface; const ajn::InterfaceDescription::Member* method; size_t numArgs; ajn::MsgArg* args = NULL; const char* begin; uint32_t timeout = ajn::ProxyBusObject::DefaultCallTimeout; uint8_t flags = 0; qcc::String noReply = "false"; bool typeError = false; iface = env->busAttachment->GetInterface(env->interfaceName.c_str()); if (!iface) { env->status = ER_BUS_NO_SUCH_INTERFACE; QCC_LogError(env->status, ("%s", env->interfaceName.c_str())); goto exit; } method = iface->GetMember(env->methodName.c_str()); if (!method) { env->status = ER_BUS_INTERFACE_NO_SUCH_MEMBER; QCC_LogError(env->status, ("%s", env->methodName.c_str())); goto exit; } numArgs = ajn::SignatureUtils::CountCompleteTypes(method->signature.c_str()); if (env->npargCount < numArgs) { env->status = ER_BAD_ARG_COUNT; QCC_LogError(env->status, ("")); goto exit; } args = new ajn::MsgArg[numArgs]; begin = method->signature.c_str(); for (size_t i = 0; i < numArgs; ++i) { const char* end = begin; env->status = ajn::SignatureUtils::ParseCompleteType(end); if (ER_OK != env->status) { QCC_LogError(env->status, ("")); goto exit; } qcc::String typeSignature(begin, end - begin); ToAny(env->plugin, env->npargs[i], typeSignature, args[i], typeError); if (typeError) { env->status = ER_BUS_BAD_VALUE; char errorMessage[128]; snprintf(errorMessage, sizeof(errorMessage), "argument %lu is not a '%s'", (unsigned long)(i + 2), typeSignature.c_str()); env->errorMessage = errorMessage; QCC_LogError(env->status, ("")); goto exit; } begin = end; } if (numArgs != env->npargCount) { NPVariant params = env->npargs[env->npargCount - 1]; if (!NPVARIANT_IS_OBJECT(params)) { env->status = ER_BUS_BAD_VALUE; char errorMessage[128]; snprintf(errorMessage, sizeof(errorMessage), "argument %d is not an object", env->npargCount - 1 + 2); env->errorMessage = errorMessage; QCC_LogError(env->status, ("")); goto exit; } NPVariant result; VOID_TO_NPVARIANT(result); NPN_GetProperty(env->plugin->npp, NPVARIANT_TO_OBJECT(params), NPN_GetStringIdentifier("timeout"), &result); if (!NPVARIANT_IS_VOID(result)) { timeout = ToUnsignedLong(env->plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { env->status = ER_BUS_BAD_VALUE; env->errorMessage = "'timeout' is not a number"; QCC_LogError(env->status, ("")); goto exit; } VOID_TO_NPVARIANT(result); NPN_GetProperty(env->plugin->npp, NPVARIANT_TO_OBJECT(params), NPN_GetStringIdentifier("flags"), &result); if (!NPVARIANT_IS_VOID(result)) { flags = ToOctet(env->plugin, result, typeError); } NPN_ReleaseVariantValue(&result); if (typeError) { env->status = ER_BUS_BAD_VALUE; env->errorMessage = "'flags' is not a number"; QCC_LogError(env->status, ("")); goto exit; } } #if !defined(NDEBUG) { qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); QCC_DbgTrace(("flags=0x%x", flags)); } #endif if (flags & ajn::ALLJOYN_FLAG_NO_REPLY_EXPECTED) { env->status = env->proxyBusObject->MethodCallAsync(*method, 0, 0, args, numArgs, 0, 0, flags); ajn::Message message(*env->busAttachment); env->thiz->ReplyHandler(message, 0); } else { env->status = env->proxyBusObject->MethodCallAsync(*method, env->thiz, static_cast(&ReplyReceiver::ReplyHandler), args, numArgs, 0, timeout, flags); } exit: delete[] args; } class ReplyHandlerContext : public PluginData::CallbackContext { public: Env env; ajn::Message message; ReplyHandlerContext(Env& env, ajn::Message& message) : env(env), message(message) { } }; virtual void ReplyHandler(ajn::Message& message, void*) { PluginData::Callback callback(env->plugin, _ReplyHandler); callback->context = new ReplyHandlerContext(env, message); env->thiz = NULL; delete this; PluginData::DispatchCallback(callback); } static void _ReplyHandler(PluginData::CallbackContext* ctx) { ReplyHandlerContext* context = static_cast(ctx); Env& env = context->env; if (ER_OK != env->status) { if (!env->errorMessage.empty()) { BusErrorHost busError(env->plugin, "BusError", env->errorMessage, env->status); env->callbackNative->onCallback(busError); } else { BusErrorHost busError(env->plugin, env->status); env->callbackNative->onCallback(busError); } } else if (ajn::MESSAGE_ERROR == context->message->GetType()) { QStatus status = ER_BUS_REPLY_IS_ERROR_MESSAGE; qcc::String errorMessage; const char* errorName = context->message->GetErrorName(&errorMessage); if (errorName && !strcmp(ajn::org::alljoyn::Bus::ErrorName, errorName) && context->message->GetArg(1)) { status = static_cast(context->message->GetArg(1)->v_uint16); } /* * Technically, an empty error message field is not the same as no error message field, * but treat them the same here. */ if (errorName) { qcc::String name(errorName); BusErrorHost busError(env->plugin, name, errorMessage, status); env->callbackNative->onCallback(busError); } else { BusErrorHost busError(env->plugin, status); env->callbackNative->onCallback(busError); } } else { MessageHost messageHost(env->plugin, env->busAttachment, context->message); size_t numArgs; const ajn::MsgArg* args; context->message->GetArgs(numArgs, args); #if !defined(NDEBUG) qcc::String str = ajn::MsgArg::ToString(args, numArgs); QCC_DbgTrace(("%s", str.c_str())); #endif env->callbackNative->onCallback(env->status, messageHost, args, numArgs); } } }; class _ProxyBusObjectHostImpl { public: std::map children; }; _ProxyBusObjectHost::_ProxyBusObjectHost(Plugin& plugin, BusAttachment& busAttachment, const char* serviceName, const char* path, ajn::SessionId sessionId) : ScriptableObject(plugin), busAttachment(busAttachment), proxyBusObject(*busAttachment, serviceName, path, sessionId) { QCC_DbgTrace(("%s(serviceName=%s,path=%s,sessionId=%u)", __FUNCTION__, serviceName, path, sessionId)); Initialize(); } _ProxyBusObjectHost::_ProxyBusObjectHost(Plugin& plugin, BusAttachment& busAttachment, ajn::ProxyBusObject* proxyBusObject) : ScriptableObject(plugin), busAttachment(busAttachment), proxyBusObject(*proxyBusObject) { QCC_DbgTrace(("%s", __FUNCTION__)); Initialize(); } void _ProxyBusObjectHost::Initialize() { impl = new _ProxyBusObjectHostImpl(); ATTRIBUTE("path", &_ProxyBusObjectHost::getPath, 0); ATTRIBUTE("serviceName", &_ProxyBusObjectHost::getServiceName, 0); ATTRIBUTE("sessionId", &_ProxyBusObjectHost::getSessionId, 0); ATTRIBUTE("secure", &_ProxyBusObjectHost::getSecure, 0); OPERATION("getChildren", &_ProxyBusObjectHost::getChildren); OPERATION("getInterface", &_ProxyBusObjectHost::getInterface); OPERATION("getInterfaces", &_ProxyBusObjectHost::getInterfaces); OPERATION("introspect", &_ProxyBusObjectHost::introspect); OPERATION("methodCall", &_ProxyBusObjectHost::methodCall); OPERATION("parseXML", &_ProxyBusObjectHost::parseXML); OPERATION("secureConnection", &_ProxyBusObjectHost::secureConnection); } _ProxyBusObjectHost::~_ProxyBusObjectHost() { QCC_DbgTrace(("%s", __FUNCTION__)); delete impl; } bool _ProxyBusObjectHost::getPath(NPVariant* result) { ToDOMString(plugin, proxyBusObject->GetPath(), *result); return true; } bool _ProxyBusObjectHost::getChildren(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; size_t numChildren; ajn::ProxyBusObject** children = NULL; std::vector hostChildren; QStatus status = ER_OK; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } numChildren = proxyBusObject->GetChildren(); children = new ajn::ProxyBusObject*[numChildren]; proxyBusObject->GetChildren(children, numChildren); for (uint32_t i = 0; i < numChildren; ++i) { ajn::ProxyBusObject* child = children[i]; qcc::String name = child->GetServiceName() + child->GetPath(); if (child->GetSessionId()) { char sessionId[32]; snprintf(sessionId, 32, ":sessionId=%u", child->GetSessionId()); name += sessionId; } if (impl->children.find(name) == impl->children.end()) { std::pair element(name, ProxyBusObjectHost(plugin, busAttachment, child)); impl->children.insert(element); } std::map::iterator it = impl->children.find(name); hostChildren.push_back(it->second); } CallbackNative::DispatchCallback(plugin, callbackNative, status, hostChildren); callbackNative = NULL; exit: delete callbackNative; delete[] children; VOID_TO_NPVARIANT(*result); return !typeError; } bool _ProxyBusObjectHost::getInterface(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String name; CallbackNative* callbackNative = NULL; InterfaceDescriptionNative* interfaceDescriptionNative = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } name = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } if (proxyBusObject->ImplementsInterface(name.c_str())) { interfaceDescriptionNative = InterfaceDescriptionNative::GetInterface(plugin, busAttachment, name); } CallbackNative::DispatchCallback(plugin, callbackNative, status, interfaceDescriptionNative); interfaceDescriptionNative = NULL; callbackNative = NULL; exit: delete interfaceDescriptionNative; delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _ProxyBusObjectHost::getInterfaces(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; size_t numIfaces; const ajn::InterfaceDescription** ifaces = NULL; InterfaceDescriptionNative** descs = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } numIfaces = proxyBusObject->GetInterfaces(); ifaces = new const ajn::InterfaceDescription*[numIfaces]; proxyBusObject->GetInterfaces(ifaces, numIfaces); descs = new InterfaceDescriptionNative*[numIfaces]; for (uint32_t i = 0; i < numIfaces; ++i) { descs[i] = InterfaceDescriptionNative::GetInterface(plugin, busAttachment, ifaces[i]->GetName()); } CallbackNative::DispatchCallback(plugin, callbackNative, status, descs, numIfaces); descs = NULL; callbackNative = NULL; exit: delete callbackNative; delete[] descs; delete[] ifaces; VOID_TO_NPVARIANT(*result); return !typeError; } bool _ProxyBusObjectHost::getServiceName(NPVariant* result) { ToDOMString(plugin, proxyBusObject->GetServiceName(), *result); return true; } bool _ProxyBusObjectHost::getSessionId(NPVariant* result) { ToUnsignedShort(plugin, proxyBusObject->GetSessionId(), *result); return true; } bool _ProxyBusObjectHost::getSecure(NPVariant* result) { ToUnsignedShort(plugin, proxyBusObject->IsSecure(), *result); return true; } bool _ProxyBusObjectHost::introspect(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); CallbackNative* callbackNative = NULL; IntrospectRemoteObjectAsyncCB* callback = NULL; bool typeError = false; QStatus status = ER_OK; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } callbackNative = ToNativeObject(plugin, args[0], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } callback = new IntrospectRemoteObjectAsyncCB(plugin, busAttachment, proxyBusObject, callbackNative); callbackNative = NULL; /* callback now owns callbackNative */ status = proxyBusObject->IntrospectRemoteObjectAsync(callback, static_cast(&IntrospectRemoteObjectAsyncCB::IntrospectCB), 0); if (ER_OK == status) { callback = NULL; /* alljoyn owns callback */ } else { callback->IntrospectCB(status, 0, 0); callback = NULL; /* IntrospectCB will delete callback */ } exit: delete callbackNative; delete callback; VOID_TO_NPVARIANT(*result); return !typeError; } bool _ProxyBusObjectHost::methodCall(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); qcc::String interfaceName; qcc::String methodName; CallbackNative* callbackNative = NULL; ReplyReceiver* replyReceiver = NULL; QStatus status = ER_OK; bool typeError = false; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } interfaceName = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } methodName = ToDOMString(plugin, args[1], typeError); if (typeError) { plugin->RaiseTypeError("argument 1 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 0 is not an object"); goto exit; } replyReceiver = new ReplyReceiver(plugin, busAttachment, proxyBusObject, interfaceName, methodName, callbackNative, &args[2], argCount - 3); callbackNative = NULL; /* replyReceiver now owns callbackNative */ if (proxyBusObject->ImplementsInterface(interfaceName.c_str())) { replyReceiver->IntrospectCB(ER_OK, 0, 0); } else if (busAttachment->GetInterface(interfaceName.c_str())) { status = proxyBusObject->AddInterface(*busAttachment->GetInterface(interfaceName.c_str())); replyReceiver->IntrospectCB(status, 0, 0); } else { status = proxyBusObject->IntrospectRemoteObjectAsync(replyReceiver, static_cast(&ReplyReceiver::IntrospectCB), 0); if (ER_OK != status) { replyReceiver->IntrospectCB(status, 0, 0); } } replyReceiver = NULL; /* alljoyn now owns replyReceiver */ exit: delete callbackNative; delete replyReceiver; VOID_TO_NPVARIANT(*result); return !typeError; } bool _ProxyBusObjectHost::parseXML(const NPVariant* args, uint32_t argCount, NPVariant* result) { bool typeError = false; QStatus status = ER_OK; qcc::String source; CallbackNative* callbackNative = NULL; if (argCount < 2) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } source = ToDOMString(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a string"); goto exit; } callbackNative = ToNativeObject(plugin, args[1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = proxyBusObject->ParseXml(source.c_str()); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } bool _ProxyBusObjectHost::secureConnection(const NPVariant* args, uint32_t argCount, NPVariant* result) { bool typeError = false; QStatus status = ER_OK; bool forceAuth = false; CallbackNative* callbackNative = NULL; if (argCount < 1) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } if (argCount > 1) { forceAuth = ToBoolean(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a boolean"); goto exit; } } callbackNative = ToNativeObject(plugin, args[argCount - 1], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } status = proxyBusObject->SecureConnectionAsync(forceAuth); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; VOID_TO_NPVARIANT(*result); return !typeError; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/AboutObjHost.cc0000644000175000017500000003556012620747066021466 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "AboutObjHost.h" #include "CallbackNative.h" #include "TypeMapping.h" #include #include #define QCC_MODULE "ALLJOYN_JS" _AboutObjHost::_AboutObjHost(Plugin& plugin, BusAttachment& busAttachment) : ScriptableObject(plugin), busAttachment(busAttachment), aboutObj(*busAttachment), aboutData(0) { QCC_DbgTrace(("%s %p", __FUNCTION__, this)); OPERATION("announce", &_AboutObjHost::announce); } _AboutObjHost::~_AboutObjHost() { QCC_DbgTrace(("%s %p", __FUNCTION__, this)); delete aboutData; aboutData = 0; } bool _AboutObjHost::announce(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); QStatus status = ER_OK; bool typeError = false; CallbackNative* callbackNative = NULL; NPVariant nplength = NPVARIANT_VOID; size_t lengthOfId = 0; size_t lengthOfLanguage = 0; size_t i; // mandatory ajn::SessionPort sessionPort = ajn::SESSION_PORT_ANY; uint8_t* AppId = NULL; qcc::String DefaultLanguage; qcc::String DeviceId; qcc::String AppName; qcc::String Manufacturer; qcc::String ModelNumber; qcc::String Description; qcc::String SoftwareVersion; // optional qcc::String DeviceName; qcc::String DateOfManufacture; qcc::String HardwareVersion; char** SupportedLanguages = NULL; qcc::String SupportUrl; /* * Pull out the parameters from the native object. */ NPVariant variant; if (argCount < 3) { typeError = true; plugin->RaiseTypeError("not enough arguments"); goto exit; } sessionPort = ToUnsignedShort(plugin, args[0], typeError); if (typeError) { plugin->RaiseTypeError("argument 0 is not a number"); goto exit; } if (!NPVARIANT_IS_OBJECT(args[1])) { typeError = true; plugin->RaiseTypeError("argument 1 is not an object"); goto exit; } callbackNative = ToNativeObject(plugin, args[2], typeError); if (typeError || !callbackNative) { typeError = true; plugin->RaiseTypeError("argument 2 is not an object"); goto exit; } /* * Mandatory parameters */ VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::APP_ID), &variant); if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetStringIdentifier("length"), &nplength) || !(NPVARIANT_IS_INT32(nplength) || NPVARIANT_IS_DOUBLE(nplength))) { plugin->RaiseTypeError("arg[1]'s AppId is not an array"); typeError = true; goto exit; } lengthOfId = ToLong(plugin, nplength, typeError); AppId = new uint8_t[lengthOfId]; for (i = 0; i < lengthOfId; ++i) { NPVariant npelem = NPVARIANT_VOID; if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &npelem)) { plugin->RaiseTypeError("get array element failed"); typeError = true; goto exit; } AppId[i] = ToOctet(plugin, npelem, typeError); NPN_ReleaseVariantValue(&npelem); if (typeError) { plugin->RaiseTypeError("array element is not a number"); goto exit; } } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::DEFAULT_LANGUAGE), &variant); if (!NPVARIANT_IS_VOID(variant)) { DefaultLanguage = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || DefaultLanguage.empty()) { typeError = true; plugin->RaiseTypeError("property 'DefaultLanguage' of argument 1 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::DEVICE_ID), &variant); if (!NPVARIANT_IS_VOID(variant)) { DeviceId = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || DeviceId.empty()) { typeError = true; plugin->RaiseTypeError("property 'DeviceId' of argument 1 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::APP_NAME), &variant); if (!NPVARIANT_IS_VOID(variant)) { AppName = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || AppName.empty()) { typeError = true; plugin->RaiseTypeError("property 'AppName' of argument 1 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::MANUFACTURER), &variant); if (!NPVARIANT_IS_VOID(variant)) { Manufacturer = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || Manufacturer.empty()) { typeError = true; plugin->RaiseTypeError("property 'Manufacturer' of argument 1 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::MODEL_NUMBER), &variant); if (!NPVARIANT_IS_VOID(variant)) { ModelNumber = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || ModelNumber.empty()) { typeError = true; plugin->RaiseTypeError("property 'ModelNumber' of argument 1 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::DESCRIPTION), &variant); if (!NPVARIANT_IS_VOID(variant)) { Description = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || Description.empty()) { typeError = true; plugin->RaiseTypeError("property 'Description' of argument 1 is undefined"); goto exit; } VOID_TO_NPVARIANT(variant); NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::SOFTWARE_VERSION), &variant); if (!NPVARIANT_IS_VOID(variant)) { SoftwareVersion = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError || SoftwareVersion.empty()) { typeError = true; plugin->RaiseTypeError("property 'SoftwareVersion' of argument 1 is undefined"); goto exit; } /* * Optional parameters */ VOID_TO_NPVARIANT(variant); if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::SUPPORTED_LANGUAGES), &variant)) { switch (variant.type) { // string case NPVariantType_String: lengthOfLanguage = 1; SupportedLanguages = new char*[lengthOfLanguage]; if (!NPVARIANT_IS_VOID(variant)) { qcc::String language = ToDOMString(plugin, variant, typeError); int32_t utf8length = language.length(); SupportedLanguages[0] = new char[utf8length + 1]; strncpy(SupportedLanguages[0], language.c_str(), utf8length); SupportedLanguages[0][utf8length] = 0; } break; // array case NPVariantType_Object: if (!NPVARIANT_IS_VOID(variant)) { if (!NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetStringIdentifier("length"), &nplength)) { plugin->RaiseTypeError("property 'SupportedLanguages' is not an array"); typeError = true; goto exit; } lengthOfLanguage = ToLong(plugin, nplength, typeError); SupportedLanguages = new char*[lengthOfLanguage]; for (i = 0; i < lengthOfLanguage; ++i) { SupportedLanguages[i] = NULL; NPVariant curValue; NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(variant), NPN_GetIntIdentifier(i), &curValue); if (!NPVARIANT_IS_VOID(curValue)) { int32_t utf8length = NPVARIANT_TO_STRING(curValue).UTF8Length; SupportedLanguages[i] = new char[utf8length + 1]; strncpy(SupportedLanguages[i], NPVARIANT_TO_STRING(curValue).UTF8Characters, utf8length); SupportedLanguages[i][utf8length] = 0; } NPN_ReleaseVariantValue(&curValue); } } break; default: lengthOfLanguage = 0; break; } NPN_ReleaseVariantValue(&variant); } VOID_TO_NPVARIANT(variant); if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::DEVICE_NAME), &variant)) { if (!NPVARIANT_IS_VOID(variant)) { DeviceName = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'DeviceName' is not a string"); goto exit; } } VOID_TO_NPVARIANT(variant); if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::DATE_OF_MANUFACTURE), &variant)) { if (!NPVARIANT_IS_VOID(variant)) { DateOfManufacture = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'DateOfManufacture' is not a string"); goto exit; } } VOID_TO_NPVARIANT(variant); if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::HARDWARE_VERSION), &variant)) { if (!NPVARIANT_IS_VOID(variant)) { HardwareVersion = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'HardwareVersion' is not a string"); goto exit; } } VOID_TO_NPVARIANT(variant); if (NPN_GetProperty(plugin->npp, NPVARIANT_TO_OBJECT(args[1]), NPN_GetStringIdentifier(ajn::AboutData::SUPPORT_URL), &variant)) { if (!NPVARIANT_IS_VOID(variant)) { SupportUrl = ToDOMString(plugin, variant, typeError); } NPN_ReleaseVariantValue(&variant); if (typeError) { plugin->RaiseTypeError("'SupportUrl' is not a string"); goto exit; } } /* * TODO * localized is not supported. */ delete aboutData; aboutData = 0; aboutData = new ajn::AboutData(); status = aboutData->SetDefaultLanguage(DefaultLanguage.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set default language fail"); goto exit; } status = aboutData->SetAppId(AppId, lengthOfId); if (ER_OK != status) { plugin->RaiseTypeError("set AppId fail"); goto exit; } status = aboutData->SetDeviceId(DeviceId.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set device id fail"); goto exit; } status = aboutData->SetAppName(AppName.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set app name fail"); goto exit; } status = aboutData->SetManufacturer(Manufacturer.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set manufacturer fail"); goto exit; } status = aboutData->SetModelNumber(ModelNumber.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set model number fail"); goto exit; } //aboutData->SetSupportedLanguage(SupportedLanguages.c_str()); status = aboutData->SetDescription(Description.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set description fail"); goto exit; } status = aboutData->SetSoftwareVersion(SoftwareVersion.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set software version fail"); goto exit; } /* * optional */ if (!DeviceName.empty()) { status = aboutData->SetDeviceName(DeviceName.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set device name fail"); goto exit; } } if (!DateOfManufacture.empty()) { status = aboutData->SetDateOfManufacture(DateOfManufacture.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set date of manufacture fail"); goto exit; } } if (!HardwareVersion.empty()) { status = aboutData->SetHardwareVersion(HardwareVersion.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set hardware version fail"); goto exit; } } if (!SupportUrl.empty()) { status = aboutData->SetSupportUrl(SupportUrl.c_str()); if (ER_OK != status) { plugin->RaiseTypeError("set support url fail"); goto exit; } } if (!aboutData->IsValid()) { delete aboutData; aboutData = 0; plugin->RaiseTypeError("about data is invalid"); goto exit; } status = aboutObj->Announce(sessionPort, *aboutData); CallbackNative::DispatchCallback(plugin, callbackNative, status); callbackNative = NULL; exit: delete callbackNative; delete[] AppId; for (i = 0; i < lengthOfLanguage; ++i) delete[] SupportedLanguages[i]; delete[] SupportedLanguages; NPN_ReleaseVariantValue(&nplength); VOID_TO_NPVARIANT(*result); return !typeError; } alljoyn-15.09a+dfsg.1/alljoyn_js/jni/SessionOptsInterface.h0000644000175000017500000000245112620747066023070 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _SESSIONOPTSINTERFACE_H #define _SESSIONOPTSINTERFACE_H #include "ScriptableObject.h" #include class _SessionOptsInterface : public ScriptableObject { public: static std::map& Constants(); _SessionOptsInterface(Plugin& plugin); virtual ~_SessionOptsInterface(); private: static std::map constants; }; typedef qcc::ManagedObj<_SessionOptsInterface> SessionOptsInterface; #endif // _SESSIONOPTSINTERFACE_H alljoyn-15.09a+dfsg.1/alljoyn_js/jni/PluginData.cc0000644000175000017500000001455512620747066021154 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "PluginData.h" #include "BusNamespace.h" #include "HostObject.h" #include "NativeObject.h" #include #include #define QCC_MODULE "ALLJOYN_JS" static void _DestroyOnMainThread(PluginData::CallbackContext*) { } PluginData::_Callback::_Callback(Plugin& plugin, void(*callback)(CallbackContext*)) : callback(callback), context(NULL), plugin(plugin), key(0) { } PluginData::_Callback::_Callback() : callback(NULL), context(NULL), key(0) { } PluginData::_Callback::~_Callback() { if (gPluginThread == qcc::Thread::GetThread()) { delete context; } else { PluginData::DestroyOnMainThread(plugin, context); } } void PluginData::_Callback::SetEvent() { if (!context->event.IsSet()) { QStatus setStatus = context->event.SetEvent(); setStatus = setStatus; /* Fix compiler warning in release builds. */ assert(ER_OK == setStatus); if (ER_OK != setStatus) { QCC_LogError(setStatus, ("SetEvent failed")); } } } std::list PluginData::pendingCallbacks; uintptr_t PluginData::nextPendingCallbackKey = 1; qcc::Mutex PluginData::lock; void PluginData::DispatchCallback(PluginData::Callback& callback) { if (callback->plugin->npp) { lock.Lock(); callback->key = nextPendingCallbackKey; if (++nextPendingCallbackKey == 0) { ++nextPendingCallbackKey; } pendingCallbacks.push_back(callback); lock.Unlock(); NPN_PluginThreadAsyncCall(callback->plugin->npp, PluginData::AsyncCall, (void*)callback->key); } } void PluginData::DestroyOnMainThread(Plugin& plugin, PluginData::CallbackContext* context) { lock.Lock(); if (plugin->npp) { PluginData::Callback callback(plugin, _DestroyOnMainThread); callback->context = context; callback->key = nextPendingCallbackKey; if (++nextPendingCallbackKey == 0) { ++nextPendingCallbackKey; } pendingCallbacks.push_back(callback); lock.Unlock(); NPN_PluginThreadAsyncCall(callback->plugin->npp, PluginData::AsyncCall, (void*)callback->key); } else { lock.Unlock(); /* * It is not safe to release NPAPI resources from outside the main thread. So this * could lead to a crash if called, or a memory leak if not called. Prefer the memory * leak. */ QCC_LogError(ER_WARNING, ("Leaking callback context")); } } void PluginData::CancelCallback(PluginData::Callback& callback) { lock.Lock(); if (callback->plugin->npp) { for (std::list::iterator it = pendingCallbacks.begin(); it != pendingCallbacks.end(); ++it) { if (((*it)->plugin->npp == callback->plugin->npp) && ((*it)->callback == callback->callback) && ((*it)->context == callback->context)) { pendingCallbacks.erase(it); break; } } } lock.Unlock(); } void PluginData::AsyncCall(void* key) { Callback callback; lock.Lock(); for (std::list::iterator it = pendingCallbacks.begin(); it != pendingCallbacks.end(); ++it) { if ((*it)->key == (uintptr_t)key) { callback = *it; pendingCallbacks.erase(it); break; } } lock.Unlock(); if (callback->callback) { callback->callback(callback->context); callback->SetEvent(); } } std::list PluginData::npobjects; void PluginData::InsertNPObject(NPObject* npobj) { #if defined(NDEBUG) lock.Lock(); npobjects.push_back(npobj); lock.Unlock(); #else QCC_UNUSED(npobj); #endif } void PluginData::RemoveNPObject(NPObject* npobj) { #if defined(NDEBUG) lock.Lock(); npobjects.remove(npobj); lock.Unlock(); #else QCC_UNUSED(npobj); #endif } void PluginData::DumpNPObjects() { #if defined(NDEBUG) lock.Lock(); std::list::iterator it = npobjects.begin(); if (it != npobjects.end()) { QCC_DbgHLPrintf(("Orphaned NPObjects")); } for (; it != npobjects.end(); ++it) { QCC_DbgHLPrintf(("%p", *it)); } lock.Unlock(); #endif } PluginData::PluginData(Plugin& plugin) : plugin(plugin), busNamespace(plugin) { QCC_DbgTrace(("%s", __FUNCTION__)); } PluginData::~PluginData() { QCC_DbgTrace(("%s", __FUNCTION__)); lock.Lock(); plugin->npp = 0; /* * Clear out native object cache as Firefox will delete these regardless of the reference count * when destroying the plugin. */ for (std::map::iterator it = plugin->nativeObjects.begin(); it != plugin->nativeObjects.end(); ++it) { if (it->second) { it->second = 0; it->first->Invalidate(); } } for (std::list::iterator it = pendingCallbacks.begin(); it != pendingCallbacks.end();) { if (plugin.iden((*it)->plugin)) { Callback callback = *it; callback->SetEvent(); pendingCallbacks.erase(it); /* * Can't make any assumptions about the contents of pendingCallbacks after the above * call, so reset the iterator. */ it = pendingCallbacks.begin(); } else { ++it; } } lock.Unlock(); } NPObject* PluginData::GetScriptableObject() { QCC_DbgTrace(("%s", __FUNCTION__)); return HostObject::GetInstance(plugin, busNamespace); } Plugin& PluginData::GetPlugin() { return plugin; } void PluginData::InitializeStaticData() { permissionLevels.clear(); } alljoyn-15.09a+dfsg.1/alljoyn_js/alljoyn64.reg0000644000175000017500000000076012620747066020347 0ustar debiandebianÿþWindows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@alljoyn/alljoynplugin] "Path"="C:\\AllJoyn\\npalljoyn.dll" "ProductName"="Alljoyn browser plugin" "Version"="2.0.1" "Vendor"="www.alljoyn.org" alljoyn-15.09a+dfsg.1/alljoyn_js/res/0000755000175000017500000000000012620747066016614 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/res/drawable-hdpi/0000755000175000017500000000000012620747066021317 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/res/drawable-hdpi/icon.png0000644000175000017500000000427312620747066022763 0ustar debiandebian‰PNG  IHDRHHÚ$tRNSn¦‘ pHYs  šœ[IDAThÕšéWYÆŸT¥²²!1@JAvDqmô°©´QA¶°Š"›ÊÖ=íiܵÛlÇ%œ3ÝgúØÇ…¿i>#“@’Š•ýœç[ªêÞ_î›÷¾÷­~ „ 9 ü3œŸ$’l*ÈŽ?X ()¡4®§Ã’Ôú°šÉs¿Œ’cu/é'&¥ÙÙ\OêD„–6YŽ ýqÿ⟲*÷$!Ž|ò”¶.h‡†Ä „XÌõ4J¦Vd–å·>úçøâìøâlÃíKJmB" ®¯7ͽ¥­ ÆGCדõX1ÛRë~î»ð߇6ªñÅÙ¤¼Lû§BšŽ¸s‡¶.ÐÖúÝ|øÏSA{×ôÒ Ä"cbtYßi;Í5“g®”.}qÄ’´4R&ÇÉäW•Z¶·ùh÷‹©±Ï3Ë©ÎÍÝ Ó.&Äâð«×Ø¢žÿ¦éè Ø´‰“ù¯ J(HÙ“Õpgxäǵûôì@G­0@ä|—,7—ž{ëÀFÏ[*ËËùJ¥ÿA¾J,•D¥Ä6Ýuà±»õá¡‘úï%¥ÒP‹…~ûΑͺ@[ ¿ÞU(æ«Tl膤èÒž“} ¿¬F5¾8›Q–ïâ IIÆûV£­ ¦¹·Ú¾þÀÌLB´Â‚ûDÂñöª¢îS£Ÿ¹ j›žX1íâ Á'O­f‹ÌÈÇÓšÎ.¾Zí[$‰B¶¥ð»ög?¹à±yè÷{1™îÓ)“ïÝwÅfË+³ÏUG«ö‘(¡`}ZbÅP‹s†pöØç™²þÆ€ ©'OV”4½™sËF¿›¿rU–“C²F% ’–œ9qöÍõ±O®bÏîžW×Ö§%ò<Û‘(F72êìËÒiEÑÑߊ¤Ë>²ÿüümOxìÎ;QÎh”ÀôôÈé'²Ù|ºQh2ñ(Š1’X*‰Û‘Vó‚ë áìîS2µ‚ÑX„X¬éìbFÏ[#nÞTVT0Ûñt"+.´0]¨ñÅÙ‘O·•0û ”^ozý†›uÁôêõº±ñÀôt÷K¨ Ú}ªbøý4S$[Ψþ¡‹érÙ¥®©Ym¿vkÝðæêéQ©q=/¯zA5¾8{~þvâ®t¯kJ§ÓÿtÙ;0Úº ËËóXù`³0ÀûÓ$å%%Q/_®-°ÿÜ QyMe!kרèÇgyæ²o¤²Ior®ú¹kyðÃjUh#— Ï‚¡ô[PW‰Ô$£ÇðHR]sÜ'`ÿ|˜’ŸÅŒJ„üh;¡ŽÿsO#Šó¬qMÊåQ³ÏYýø´¸Û, ðh <‚¤Ø’„ž&G¤åîmAþNF‘)ËË3½Y¹™å%Ø™_1&oôhp’DÜTZŠ=·®«Dj"<{¥ÂÖ ³ VØú=Ÿâ»Y¥ÀÝèª÷iyd)Eh°ûç„4kûФ7`=/¯R"«Ûl±·3ƒ1’CdîÛMˆëÈäQTh[ `ÃM»~ 18zÐ{¤å®¯ÆÖH%.¤t:ç,¬fâ¬,xõþ¸Jò"t7°Cµ´tÍ8\ c¸‹yªÍæoë}{kcÖæ•/ VbgzÙDrðÞhCÁ_aÇ£´ZýÄ=oõìàÙS”Ðé×%!>æÃh÷!ÕPÛÑ|ÙÿpŽLIå,H`Ãï§Õz§N¿Nƒ²"tŸö-Òr÷µ¢úÖG:+¤B¡a 6òáIö‘¢¯T äf¡¯ÕHËÝ߆#¥Ð„€ÿu×EG›¾ôú=k¸uIµîË …¤%ãÄa ´qCewkv¤C)·OXÓÑÉlèû‡ö$ ‚‡ua¨Øs.‹#ú|+ª±a)2E±±¶ªß#°êñNa j% sÑÛÂ=Œ³ûÛPU‚¨žP¨()1½|å¬ýɤ>-[’qê(÷®ÝÕ€]Û¨øXýä¤{°LK a®ÂÙ5{n–΂ú£Òz³0Q°Š_¼gX­$|ísͨ­àGEº’DâFçn]_ŒTH=ü»Ž­ZO‰wsRäÖ½-(Ì…ZÉ´Ë 7 ­uÜc,wO#J œg¹F=ÊŠÖD:é³àx¹½ Õ% @|4Ç@O27CäE÷Îe¥áô÷è÷o^i?‰}9Pù€Ç.‚€6{v Ë/[Bo ªŠAáIÇ…   ¨)à/d͵HŽó8•³(’ĆH4Tã<«g™6´Ö!g›¿Vi5)娑ަÖb¯à;„ë|“!˜ŠÏGˆåûÑÿ ¶ÁvÔU"††Àe«?]žÏóºçyîž{„&Æ—¬É$µPbP0Ö[_N¿z²ÝðÙlM H«Tÿ TQUÙ5Xx|'rs‘áXy½Ó¶ñÐòÓmå[í dßFξÙë‹mÿÈ$Ÿ¬Y]/e¯ë†ÃŽTÚ‘J×­¬(š›ËeM×»_‰ÜZZÞ½ŸÈ$™d_|„ü3™V{xõç¬gô»n<Ê<Š*EÒug.O.=]Ï2‰LráÏUA›ßFÝÝŲi]¿WÝ×G1Œæ@Uå‰á…¿VsL6ß ùy-)š6_¿žï9RiË­•­mMaŽuùÚf|ŸØMò¤©ä· •RàÎÜnûæ&Ïslm›—8»}ÏYµ4;?º:ÿ<“È$—wïíh¬¢1Æã|,»µÃaZ­æ×´ôuæž‚çóÜw1»çJ°f‹í×ß=G*mMþ ÿ)8=ÚKºüt½®ÑVhö)ªvhh/Ì‘Js6»X¬7.$ˆRi]»[.Û¹¡Ö×ŨŽwlï”…µ œ# Xö…+_—ŽE×Vä*Db*ޱon•ˆ5x\â% Äpaºlð›9JúFÇèõ¶Ò°…ÇwL V©R6jΤa§ÆƒÂ=Qì Ðu ªJÁ&D©4߸)›}t­JW-ÐF÷»ðù8.MáÒ¦>†Û¡=¾²ÝëØI‰Â<½>~5#C«3‘gL~žë‡¹Ž?~–5-'ŠcÑÕ¯¨üÏ<¡à´alP€Éåü$zN¢º*¿CÎá°om–žÜu¾qôß«ºZôwã‹h!)—Ÿ†Ñò:8.W­NÂÎ&.<ÇÂëÁ܈(&?#AØg?cŒÞ`]¿'ŒÍÿq[{ÈBÐÔ€èyÉLþ¬öwC[@ÓÓ#ŒPF=ÎøŸ(]Êåܼ¢­=tõk ¾'÷û07ºL~Ž*‡|Œ6éúó“ûŒ]…ÏK)à‡L†æFŒ|ÊÅg|ï +x’TÈñv .–7ŸŸ„ðb½è«Z§Ø7,?§Ãð¼™L“ B`5ã|¿Ø…ŒátÔåü×Èdp5a:\Dü¦RúüsèhìІ2BSã>1¹ (þV9×9W¼¶Ä  6D‚ðw¢F#µúo…ŽØtŠ:IEND®B`‚alljoyn-15.09a+dfsg.1/alljoyn_js/res/drawable-ldpi/0000755000175000017500000000000012620747066021323 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/res/drawable-ldpi/icon.png0000644000175000017500000000226612620747066022767 0ustar debiandebian‰PNG  IHDR00Ø`nÐtRNSn¦‘ pHYs  šœVIDATX…ÅØÿOgðwpx|)ˆ0J@ËIgç÷ÙŽ´ÕÚŽˆZ­q~I§ƒ…)³²)h¥Ö2uD«d_šn]Ú™&6´I­#kfÚTèKš41áoÚg¯78îîÐOÞ?qÏ}î%Ü=÷<ˆQJ£¡EEi%´p•¢Þá›AóO?+Σ¤ Ô9àŽ¾Ùºùâ>*A}î"’)ÓÚÌb9Mõ™ú¹í»±t"–NÔ´¶Vüò+‘L¯÷ôªTEg1z7n”X:ñí?R‡J"™"s⯄¦§·¸7–LŽwOyÖÞ=£4ëû;ÙÌô1ÇÃ7(‘LUnnÊŠ¢i齸´÷ˆ¢éŸ÷g “hµ'þ~A7É”qi3™D£TÖ9‚ñX%–NDßlá*EöxíÕ« "™²¿|¥óùDÑt#«¡l 瀛ñ,ì[³MD2Uµý\ÝÁ|GIe˜klèöÛ§¹4sÛwQIÎVyö#ˆLŽ{xMMšF÷ù[»rQÈTŸ©gobÞØ`1ÉÔñ› ­–ƒbrØ&®°Sbé„w#ÌùWÉl6âõ»ÉþÏ®vtÁ0æ‘õýNÍÚ»gº #' Á;ˆŒ-þ„ù¼Æã»‰¥ÝS>@•Êì)€1òz¦¹Šhiï‘LžÇ£«éë+.¨¥÷ ” h埛Åã±¼4dÉ›š‹ª¬sÓêªø /WC…i3™ì/_‰ ºýö©Æ +ºñq1A®±A!@•ʪíçâ€ní>ÊrL¦ù”º«[P£û¼p Y–ßï ]{¸"–ðÚZA õý“ÃÆ}ê*ŽAg;ड़c‘  -~ÇѾ¼ Fûa%|ù4œb?C¢×gO¼@+ÿÆeÇr6–JÀÕ Ë³4T&¾3Ûr Üë-tÁÓ—³eÝÇp}‚B%:W:@!g<Á0[üI~ r3Ê0H_¾a6 =‘i8Ý’ÝFÕ~1?ÐɳM™‡ñRèl‡è_ •)XÍÙ—;Øæòÿ¶˜y¬áÌò¦Ð3xÔ*zËR‡ƒZã²27£f#øGQ¨,† í3J¨Þ†ÙëÜ žÐ×~£+…üFì™ñCuyj››t°E8Ý ß‹L¡Ç3åeð~››äpƒÅ“Þ"R¨,Ï‚«µDŽ[·3ƒº&¡žÃ ÐžTø<Ì ¬¾“‡ Z ÃàeD£fH%péó ¡™ô2NQY¥VÁpoq)óhªåA¡—Õ\”»{y:Úø,TrÔ§õBçhzÞ?í /…Ž6¡3ä”ìVÁz•—g JdœÍŒï|1Ên…à_Jtz\nž… àl†È4‡Æ7 }‘)ôbyõÎøá¤ý)ô2èÿ·€ŒLg,0ލ>qÀŒ¾è¦[ç[ÿÙ´oãŸpHIEND®B`‚alljoyn-15.09a+dfsg.1/alljoyn_js/res/layout/0000755000175000017500000000000012620747066020131 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/res/layout/permission_dialog.xml0000644000175000017500000000160112620747066024360 0ustar debiandebian alljoyn-15.09a+dfsg.1/alljoyn_js/res/xml/0000755000175000017500000000000012620747066017414 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/res/xml/preferences.xml0000644000175000017500000000100112620747066022427 0ustar debiandebian alljoyn-15.09a+dfsg.1/alljoyn_js/res/values/0000755000175000017500000000000012620747066020113 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/res/values/strings.xml0000644000175000017500000000151512620747066022330 0ustar debiandebian AllJoyn browser plugin AllJoyn plugin settings Security Warning The website below wants to use AllJoyn. Do you want to allow this? Remember my decision for this site Allow Deny Clear AllJoyn Clear all saved authorizations and passwords Clear alljoyn-15.09a+dfsg.1/alljoyn_js/jsunit.sh0000755000175000017500000000746312620747066017710 0ustar debiandebian# Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # function cleanup { killall -1 chrome alljoyn-daemon java >/dev/null 2>&1 && s killall -9 chrome alljoyn-daemon java >/dev/null 2>&1 && s } function s { if [ "`hostname | grep isk | wc -l`" == "1" ] ; then sleep 30 fi if [ "$1" == "" ] ; then for i in {1..3} do sleep 1 echo -n . done else for i in $(eval echo "{1..$1}"); do sleep 1 echo -n . done fi echo . } function startservers { java -jar /opt/JsTestDriver/JsTestDriver.jar --port 4224 --browserTimeout 90000 > /dev/null 2>&1 & JAVASERVERPID=$! s if [ "`ps aux | grep $JAVASERVERPID | grep -v grep | wc -l`" == "0" ] ; then bail "java server could not start on port 4224; need to kill old java process" fi if [ "`ps aux | grep alljoyn-daemon | grep -v grep | wc -l`" != "0" ] ; then bail "old alljoyn-daemons hanging around" fi $INSTALLDIR/dist/bin/alljoyn-daemon > /dev/null 2>&1 & ALLJOYNDAEMONPID=$! if [ "`ps aux | grep $ALLJOYNDAEMONPID | grep -v grep | wc -l`" == "0" ] ; then bail "alljoyn-daemon could not start" fi s } function startbrowsers { google-chrome --load-plugin=$INSTALLDIR/dist/js/lib/libnpalljoyn.so http://localhost:4224/capture > /dev/null 2>&1 & if [ "`hostname | grep isk | wc -l`" == "1" ] ; then s 90 else s 20 fi } function executetests { echo TEST OF $1 BEGINS java -jar /opt/JsTestDriver/JsTestDriver.jar --config jsTestDriver-npapi.conf --tests $1 --testOutput $TESTDIR if [ $? -ne 0 ] ; then FAIL=YES fi s echo TEST OF $1 ENDS } function testjs { cleanup startservers startbrowsers executetests $1 cleanup } function bail { echo "FAILFAILFAIL: " $1 cleanup exit 1 } function results { TC=`ls $TESTDIR/*xml|wc -l` if [ "$TC" -eq "0" ] ; then bail "No Test Results." fi NF=`grep \ alljoyn-15.09a+dfsg.1/alljoyn_js/docs/0000755000175000017500000000000012620747066016753 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/docs/alljoyn_doc.js0000644000175000017500000013364112620747066021616 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * NOTE: This documentation is only a reflection of the AllJoyn JavaScript API. * AllJoyn for JavaScript is developed using NPAPI and has very little actual * JavaScript code. This documentation is so developers can develop programs * using the JavaScript API. */ /** * @fileOverview * * AllJoyn™ JavaScript API Reference Manual * @version 15.09.00 * @description * Type coercion between DBus and JavaScript types is done according to the following table. * * * * * * * * * * * * * * * * * *
IDL typeDBus typeSignatureJavaScript * type
octetBYTE'y'Number
booleanBOOLEAN'b'Boolean
shortINT16'n'Number
unsigned shortUINT16'q'Number
longINT32'i'Number
unsigned longUINT32'u'Number
long longINT64'x'The DBus value is coerced into a decimal * string. Use parseInt to convert the argument to a number if loss of precision is not a * concern.
unsigned long longUINT64't'The DBus value is coerced into a * decimal string. Use parseInt to convert the argument to a number if loss of precision * is not a concern.
doubleDOUBLE'd'Number
DOMStringSTRING's'String
DOMStringOBJECT_PATH'o'String
DOMStringSIGNATURE'g'String
sequence<T>ARRAY'a'When the DBus value is an array of * DICT_ENTRY, the argument will be an Object where each property is the DICT_ENTRY key and each * value is the DICT_ENTRY value. Otherwise the argument will be an Array.
sequence<any>STRUCT'r', '(', ')'Array
anyVARIANT'v'DBus VARIANT types remove the VARIANT wrapper. * For example, a VARIANT of the string "value" will be "value". Nested VARIANTs will * remove only one VARIANT wrapper. For example, a VARIANT of a VARIANT of a string will be the * Object { "s": "value" }.
* * Debug output of the plugin can be configured dynamically by setting the debug attribute of the * object element containing the plugin. The syntax of the attribute value is the same as * BusAttachment.setDaemonDebug, e.g. debug="ALLJOYN_JS=15". The destination for debug * output depends on the platform: Windows is OutputDebugString, and for all * others it is stdout. */ /** {Number} SessionId uniquely identifies an AllJoyn session instance (range 0 to 4,294,967,295). */ var SessionId; /** * {Number} SessionPort identifies a per-BusAttachment receiver for incoming JoinSession * requests. (range 0 to 65,535) * * SessionPort values are bound to a BusAttachment when the attachment calls * BindSessionPort. * * NOTE: Valid SessionPort values range from 1 to 0xFFFF. */ var SessionPort; /** {Number} Bitmask of all transport types (mask values 0 to 0xFF)*/ var TransportMask; /** {Number} Status code value (range 0 to 65,535)*/ var Status; /** * @class * @name BusError * @description * AllJoyn-specific error codes. * * Note that NPAPI does not support raising custom exceptions, and the browsers behave * differently. To workaround this, the plugin provides the name, message, and code * fields of the most recently raised exception on the exception interface object. */ var BusError = Class.create( /** * @lends BusError */ { /** * * The error name. * * The default value is "BusError". * @type {String} */ name: "BusError", /** * The error message. * * The default value is the empty string. * @type {String} */ message: "", /** * The error code. * @type {Status} */ code: Status }); /** * @class * @name AuthListener * @description * Interface to allow authentication mechanisms to interact with the user or * application. */ var AuthListener = Class.create( /** * @lends AuthListener */ { /** * The authentication mechanism requests user credentials. * * If the user name is not an empty string the request is for credentials for that * specific user. A count allows the listener to decide whether to allow or reject * multiple authentication attempts to the same peer. * * @param {String} authMechanism the name of the authentication mechanism issuing the request * @param {String} peerName the name of the remote peer being authenticated. On the * initiating side this will be a well-known-name for the remote * peer. On the accepting side this will be the unique bus name for * the remote peer. * @param {Number} authCount count (starting at 1) of the number of authentication request * attempts made (number range 0 to 65,535) * @param {String} userName the user name for the credentials being requested * @param {Number} credMask a bit mask identifying the credentials being requested. The * application may return none, some or all of the requested * credentials. (bit mask range 0 to 0xFF) * @param {Credentials} credentials the credentials returned * * @return {boolean} the caller should return true if the request is being accepted or false * if the requests is being rejected. If the request is rejected the * authentication is complete. */ onRequest: function(authMechanism, peerName, authCount, userName, credMask, credentials) { }, /** * The authentication mechanism requests verification of credentials from a * remote peer. * * This operation is mandatory for the ALLJOYN_ECDHE_ECDSA auth mechanism, optional * for others. * * @param {String} authMechanism the name of the authentication mechanism issuing the request * @param {String} peerName the name of the remote peer being authenticated. On the * initiating side this will be a well-known-name for the remote * peer. On the accepting side this will be the unique bus name for * the remote peer. * @param {Credentials} credentials the credentials to be verified * * @return {boolean} the listener should return true if the credentials are acceptable or * false if the credentials are being rejected. */ onVerify: function(authMechanism, peerName, credentials) { }, /** * Optional operation that if implemented allows an application to monitor * security violations. * * This operation is called when an attempt to decrypt an encrypted messages failed * or when an unencrypted message was received on an interface that requires * encryption. The message contains only header information. * * @param {Status} status a status code indicating the type of security violation * @param {Message} context the message that cause the security violation */ onSecurityViolation: function(status, context) { }, /** * Reports successful or unsuccessful completion of authentication. * * @param {String} authMechanism the name of the authentication mechanism that was used or an * empty string if the authentication failed * @param {String} peerName the name of the remote peer being authenticated. On the * initiating side this will be a well-known-name for the remote * peer. On the accepting side this will be the unique bus name for * the remote peer. * @param {boolean} success true if the authentication was successful, otherwise false */ onComplete: function(authMechanism, peerName, success) { } }); /** * @namespace * @name org */ var org = org || {}; /** @namespace */ org.alljoyn = {}; /** @namespace */ org.alljoyn.bus = {}; /** * BusAttachment is the top-level object responsible for connecting to and optionally * managing a message bus. * @constructor */ org.alljoyn.bus.BusAttachment = function() { /** * Value for requestName flags bit corresponding to allowing another bus * attachment to take ownership of this name. * @constant */ this.DBUS_NAME_FLAG_ALLOW_REPLACEMENT = 0x01; /** * Value for requestName flags bit corresponding to a request to take * ownership of the name in question if it is already taken. * @constant */ this.DBUS_NAME_FLAG_REPLACE_EXISTING = 0x02; /** * Value for requestName flags bit corresponding to a request to fail if the * name in question cannot be immediately obtained. * @constant */ this.DBUS_NAME_FLAG_DO_NOT_QUEUE = 0x04; /** * Invalid SessionPort value used to indicate that bindSessionPort should * choose any available port. * @constant */ this.SESSION_PORT_ANY = 0; /** * The GUID of this BusAttachment. * * The returned value may be appended to an advertised well-known name in order to * guarantee that the resulting name is globally unique. * * Read-only. * @type {String} */ this.globalGUIDString; /** * The unique name of this BusAttachment. * * Read-only. * * null if not connected. * @type {String} */ this.uniqueName; /** * Adds a logon entry string for the requested authentication mechanism to the key store. * * This allows an authenticating server to generate offline authentication * credentials for securely logging on a remote peer using a user-name and password * credentials pair. This only applies to authentication mechanisms that support a * user name + password logon functionality. * * @param {String} authMechanism the authentication mechanism * @param {String} userName the user name to use for generating the logon entry * @param {String} password the password to use for generating the logon entry. If the * password is null the logon entry is deleted from the key * store. * @param {statusCallback} callback function that should be run after the logonEntry has * been added. Status will be OK if the logon entry was generated. * BUS_INVALID_AUTH_MECHANISM if the authentication mechanism * does not support logon functionality. * Other error status codes indicating a failure. */ this.addLogonEntry = function(authMechanism, userName, password, callback) {}; /** * Adds a DBus match rule. * * This operation is a shortcut/helper that issues an org.freedesktop.DBus.AddMatch method call * to the local daemon. * * @param {String} rule match rule to be added (see DBus specification for format of this string) * @param {statusCallback} callback function to run after addMatch has completed. callback will contain * status BUS_NOT_CONNECTED if a connection has not been made with a local bus. * Other error status codes indicating a failure. */ this.addMatch = function(rule, callback) {}; /** * Advertises the existence of a well-known name to other (possibly disconnected) * AllJoyn daemons. * * This operation is a shortcut/helper that issues an org.alljoyn.Bus.AdvertisedName method * call to the local daemon and interprets the response. * * @param {String} name the well-known name to advertise. (Must be owned by the caller via RequestName) * @param {TransportMask} transports set of transports to use for sending advertisment * @param {statusCallback} callback function to run after name is advertised. Callback will * contain status BUS_NOT_CONNECTED if a connection has not been * made with a local bus. * Other error status codes indicating a failure */ this.advertiseName = function(name, transports, callback){}; /** * \brief Makes a SessionPort available for external BusAttachments to join. * * Each BusAttachment binds its own set of SessionPorts. Session joiners use the bound * session port along with the name of the attachement to create a persistent logical * connection (called a Session) with the original BusAttachment. * * SessionPort and bus name form a unique identifier that BusAttachments use when joining * a session. * * SessionPort values can be pre-arranged between AllJoyn services and their clients * (well-known SessionPorts). * * Once a session is joined using one of the service's well-known SessionPorts, the service * may bind additional SessionPorts (dyanamically) and share these SessionPorts with the * joiner over the original session. The joiner can then create additional sessions with the * service by calling JoinSession with these dynamic SessionPort ids. * * The parameters are supplied as a named-parameter object literal. *
*
port
*
SessionPort value to bind. The default value is SESSION_PORT_ANY to allow * this operation to choose an available port. On successful return, this value will * be the chosen port.
*
traffic
*
TrafficType. The default value is TRAFFIC_MESSAGES.
*
isMultipoint
*
boolean indicating if session is multi-point capable. The default value is * false.
*
proximity
*
Proximity. The default value is PROXIMITY_ANY.
*
transports
*
TransportMask of the allowed transports. The default value is * TRANSPORT_ANY.
*
onAccept
*
an AcceptSessionJoinerListener to * accept or reject an incoming JoinSession request. The session does not exist until this * after this function returns.
*
onJoined
*
a SessionJoinedListener called by the bus * when a session has been successfully joined
*
onLost
*
a SessionLostListener called by the bus * when an existing session becomes disconnected
*
onMemberAdded
*
a SessionMemberAddedListener called * by the bus when a member of a multipoint session is added
*
onMemberRemoved
*
a SessionMemberRemovedListener called * by the bus when a member of a multipoint session is removed
*
* * @param {object} parameters see above * @param {sessionPortCallback} callback function run after bindSessionPort has completed. * BUS_NOT_CONNECTED if a connection has not been made with a local bus. */ this.bindSessionPort = function(parameters, callback){}; /** * Stops advertising the existence of a well-known name to other AllJoyn daemons. * * This operation is a shortcut/helper that issues an org.alljoyn.Bus.CancelAdvertiseName * method call to the local daemon and interprets the response. * * @param {String} name a well-known name that was previously advertised via AdvertiseName * @param {TransportMask} transports set of transports whose name advertisment will be cancelled * @param {statusCallback} callback function that is run after cancelAdvertiseName * callback returns * BUS_NOT_CONNECTED if a connection has not been made with a local bus * Other error status codes indicating a failure */ this.cancelAdvertiseName = function(name, transports, callback){}; /** * Cancels interest in a well-known name prefix that was previously registered with * FindAdvertisedName. * * This operation is a shortcut/helper that issues an org.alljoyn.Bus.CancelFindAdvertisedName * method call to the local daemon and interprets the response. * * @param {String} namePrefix well-known name prefix that application is no longer interested in * receiving BusListener onFoundAdvertisedName notifications about * @param {statusCallback} callback function run after a cancelFindAdvertisedName has completed * Callback will specify BUS_NOT_CONNECTED if a connection has not been made * with a local bus. * Other error status codes indicating a failure */ this.cancelFindAdvertisedName = function(namePrefix, callback){}; /** * Clears all stored keys from the key store. * * All store keys and authentication information is deleted and cannot be * recovered. Any passwords or other credentials will need to be reentered when * establishing secure peer connections. * * @param {statusCallback} callback function called after clearKeyStore has completed. */ this.clearKeyStore = function(callback) {}; /** * Clear the keys associated with a specific peer identified by its GUID. * * @param {String} guid the guid of a remote authenticated peer * @param {statusCallback} callback function that gets called after clearKeys have completed * callback will return OK if the key was cleared. * UNKNOWN_GUID if there is no peer with the specified GUID. * Other error status codes indicating a failure. */ this.clearKeys = function(guid, callback) {}; /** * Connects to a remote bus address. * * @param {String|optional} connectSpec an optional transport connection spec string of the form * "<transport>:<param1>=<value1>,<param2>=<value2>...[;]". * The default value is platform-specific. * @param {statusCallback} callback function that is called once connect has completed. */ this.connect = function(connectSpec, callback) {}; /** * create a new BusAttachment. * * create must be called before any other BusAttachment methods. This call * is responsible for making sure proper creation a native BusAttachment. * * @param {boolean} allowRemoteMessages True if this attachment is allowed to receive messages from remote devices. * @param {statusCallback} callback callback function called once the native BusAttachment has been created. */ this.create = function(allowRemoteMessages, callback) {}; /** * Add the interface specified by the interfaceDescription to the BusAttachment * * The interfaceDescription must be a full interface specification. The interface is * created and activated on the BusAttachment. * * @param {InterfaceDescription} interfaceDescription the specification for the interface being created. * @param {statusCallback} callback the function called once the createInterface method has completed. */ this.createInterface = function(interfaceDescription, callback) {}; /** * Initialize one more interface descriptions from an XML string in DBus introspection format. * The root tag of the XML can be a \ or a stand alone \ tag. To initialize more * than one interface the interfaces need to be nested in a \ tag. * * Note that when this method fails during parsing, the return code will be set accordingly. * However, any interfaces which were successfully parsed prior to the failure may be registered * with the bus. * * @param {String} xml An XML string in DBus introspection format. * @param {statusCallback} callback function that is run after creating the * interfaces from xml. Callback will specify OK if parsing is * completely successful. An error status otherwise. */ this.createInterfacesFromXML = function(xml, callback) {}; /** * Disconnects from a remote bus address connection. * * @param {statusCallback} callback function will specify BUS_NOT_STARTED if the bus is not started. * BUS_NOT_CONNECTED if the BusAttachment is not connected to the bus. * Other error status codes indicating a failure. */ this.disconnect = function(callback) {}; /** * Explicitly release the reference to the BusAttachment object * * Explicitly releasing the reference to the BusAttachment object makes it * so the JavaScript garbage-collector can free up the reference to the native * BusAttachment. * destroy should be called when the BusAttachment is no longer needed. * * @param {statusCallback} callback function that should be run once destroy method call has completed */ this.destroy = function (callback) {}; /** * Enables peer-to-peer security. * * This operation must be called by applications that want to use authentication and * encryption. * * @param {String} authMechanisms the authentication mechanism(s) to use for peer-to-peer * authentication * @param {AuthListener} [listener] an optional listener that receives password and other * authentication related requests * @param {statusCallback} callback function that is run once the call to enablePeerSecurity has completed * callback specifies status OK if peer security was enabled */ this.enablePeerSecurity = function(authMechanisms, listener, callback) {}; /** * Registers interest in a well-known name prefix for the purpose of discovery. * * This operation is a shortcut/helper that issues an org.alljoyn.Bus.FindAdvertisedName method * call to the local daemon and interprets the response. * * @param {String} namePrefix well-known name prefix that application is interested in receiving * BusListener onFoundAdvertisedName notifications about * @param {statusCallback} callback function called after the findAdvertisedName method has completed * callback returns BUS_NOT_CONNECTED if a connection has not been made with a local bus * or Other error status codes indicating a failure */ this.findAdvertisedName = function(namePrefix, callback){}; /** * Retrieve an existing activated InterfaceDescription. * * @param {String} name interface name * @param {interfaceDescriptionCallback} callback containing the specified interfaceDescritption. */ this.getInterface = function(name, callback){}; /** * Returns the existing activated InterfaceDescriptions. * * @param {interfaceDescriptionsCallback} callback containing the specified unterfaceDescritptions */ this.getInterfaces = function(callback) {}; /** * Get the expiration time on keys associated with a specific authenticated * remote peer as identified by its peer GUID. * * The peer GUID associated with a bus name can be obtained by calling * getPeerGUID. * * Throws BusError an error status. UNKNOWN_GUID if there is no authenticated peer * with the specified GUID. Other error status codes indicating a failure. * * @param {String} guid the GUID of a remote authenticated peer * @param {timeoutCallback} callback A callback function that will be sent the time in seconds relative to the * current time when the keys will expire */ this.getKeyExpiration = function(guid, callback) {}; /** * Gets the peer GUID for this peer or an authenticated remote peer. * * Peer GUIDs are used by the authentication mechanisms to uniquely and identify a * remote application instance. The peer GUID for a remote peer is only available if * the remote peer has been authenticated. * * @param {String} name name of a remote peer or null to get the local (our) peer * GUID * @param {guidCallback} callback function that will contain the guid for the local or remote peer depending on the value of name */ this.getPeerGUID = function(name, callback) {}; /** * Check to see if peer security has been enabled for this bus attachment. * * @param {securityEnabledCallback} callback function which indicates if peer security is enabled */ this.getPeerSecurityEnabled = function(callback) {}; /** * Gets a proxy to a remote bus object. * * @param {String} name the name, object path, and optional arguments of the remote object of the * form "org.sample.Foo/foo:sessionId=42" where "org.sample.Foo" is the * well-known or unique name, "/foo" is the object path, and ":sessionId=42" is * the optional session ID the be used for communicating with the remote object * @param {proxyBusObjectCallback} callback a function containing a proxy to the remote bus * object at the name and object path */ this.getProxyBusObject = function(name, callback) {}; /** * Returns the current non-absolute real-time clock used internally by AllJoyn. * * This value can be compared with the timestamps on messages to calculate the * time since a timestamped message was sent. * * @param {timestampCallback} callback function that will contain the current * timestamp in milliseconds. */ this.getTimestamp = function(callback) {}; /** * Joins a session. * * This operation is a shortcut/helper that issues an org.alljoyn.Bus.JoinSession method call * to the local daemon and interprets the response. * * The parameters are supplied as a named-parameter object literal. *
*
host
*
mandatory bus name of the attachment that is hosting the the session to be joined
*
port
*
mandatory SessionPort of host to be joined
*
traffic
*
TrafficType. The default value is TRAFFIC_MESSAGES.
*
isMultipoint
*
boolean indicating if session is multi-point capable. The default value is * false.
*
proximity
*
Proximity. The default value is PROXIMITY_ANY.
*
transports
*
TransportMask of the allowed transports. The default value is * TRANSPORT_ANY.
*
onLost
*
a SessionLostListener called by the bus * when an existing session becomes disconnected
*
onMemberAdded
*
a SessionMemberAddedListener called * by the bus when a member of a multipoint session is added
*
onMemberRemoved
*
a SessionMemberRemovedListener called * by the bus when a member of a multipoint session is removed
*
* * @param {object} parameters see above * @param {statusCallback} callback function run after joinSession method call has completed */ this.joinSession = function(parameters, callback) {}; /** * Leaves an existing session. * * This operation is a shortcut/helper that issues an org.alljoyn.Bus.LeaveSession method call * to the local daemon and interprets the response. * * @param {SessionId} id session id * @param {statusCallback} callback funtion to run after leaveSession method call has completed * BUS_NOT_CONNECTED if a connection has not been made with a local bus. * Other error status codes indicating a failure. */ this.leaveSession = function(id, callback) {}; /** * Gets the file descriptor for a raw (non-message based) session. * * @param {SessionId} id ID of an existing streaming session * @param {soketFdCallback} callback callback that will contain the socket file descriptor for session */ this.getSessionFd = function(id, callback) {}; /** * Determines whether a given well-known name exists on the bus. * * This operation is a shortcut/helper that issues an org.freedesktop.DBus.NameHasOwner method * call to the daemon and interprets the response. * * @param {String} name The well known name that the caller is inquiring about * @param {hasOwnerCallback} callback callback that indicates whether name exists on the bus */ this.nameHasOwner = function(name, callback) {}; /** * Registers an object that will receive bus event notifications. * * @param {BusListener} listener the object that will receive bus event notifications * @param {statusCallback} callback function that is run after registerBusListener has completed */ this.registerBusListener= function(listener, callback) {}; /** * Registers a locally located DBus object. * * BusError BUS_BAD_OBJ_PATH if the object path is bad. * BusError BUS_OBJ_ALREADY_EXISTS if an object is already registered at this path. * * @param {String} objectPath the absolute object path of the DBus object * @param {BusObject} busObject the DBus object implementation * @param {statusCallback} callback callback function that should be run once the BusObject has * been registered */ this.registerBusObject = function(objectPath, busObject, callback){}; /** * Registers a signal handler. * * Signals are forwarded to the signal handler if the sender, interface, member and path * qualifiers are all met. * * If multiple identical signal handlers are registered with the same parameters the * duplicate instances are discarded. They do not need to be removed with the * unregisterSignalHandler operation. * * @param {MessageListener} signalListener the function called when the signal is received * @param {String} signalName the interface and member of the signal of the form * "org.sample.Foo.Echoed" where "org.sample.Foo" is * the interface and "Echoed" is the member * @param {String} [sourcePath] the object path of the emitter of the signal * @param {statusCallback} callback status callback that will contain: * BUS_NO_SUCH_INTERFACE if the interface part of signalName does not exist. * BUS_NO_SUCH_MEMBER if the member part of signalName does not exist. * Other error status codes indicating a failure. */ this.registerSignalHandler = function(signalListener, signalName, sourcePath, callback){}; /** * Releases a previously requeted well-known name. * * This operation is a shortcut/helper that issues an org.freedesktop.DBus.ReleaseName method * call to the local daemon and interprets the response. * * @param {String} name well-known name being released * @param {statusCallback} callback function that will contain the following status: * BUS_NOT_CONNECTED if a connection has not been made with a local bus. * Other error status codes indicating a failure. */ this.releaseName = function(name, callback){}; /** * Reloads the key store for this bus attachment. * * This function would normally only be called in the case where a single key store * is shared between multiple bus attachments, possibly by different * applications. It is up to the applications to coordinate how and when the shared * key store is modified. * * @param {statusCallback} callback statusCallback will contain: * OK if the key store was succesfully reloaded. * An error status indicating that the key store reload failed. */ this.reloadKeyStore = function(callback) {}; /** * Removes a DBus match rule. * * This operation is a shortcut/helper that issues an org.freedesktop.DBus.RemoveMatch * method call to the local daemon. * * @param {String} rule match rule to be removed (see DBus specification for format of this * string) * @param {statusCallback} callback The statusCallback will contain: * BUS_NOT_CONNECTED if a connection has not been made with a local bus. * Other error status codes indicating a failure. */ this.removeMatch = function(rule, callback){}; /** * Requests a well-known name. * * This operation is a shortcut/helper that issues an org.freedesktop.DBus.RequestName method * call to the local daemon and interprets the response. * * @param {String} requestedName well-known name being requested * @param {Number} [flags] optional bitmask of DBUS_NAME_FLAG_* constants. Defaults to 0. * @param {statusCallback} callback the statusCallback will contain: * BUS_NOT_CONNECTED if a connection has not been made with a local bus. * Other error status codes indicating a failure. */ this.requestName = function(DrequestedName, flags, callback){}; /** * Sets the debug level of the local AllJoyn daemon if that daemon was built in debug * mode. * * The debug level can be set for individual subsystems or for "ALL" subsystems. Common * subsystems are "ALLJOYN" for core AllJoyn code, "ALLJOYN_OBJ" for the sessions management * code, and "ALLJOYN_NS" for the TCP name services. Debug levels for specific subsystems * override the setting for "ALL" subsystems. For example if "ALL" is set to 7, but * "ALLJOYN_OBJ" is set to 1, then detailed debug output will be generated for all subsystems * except for "ALLJOYN_OBJ" which will only generate high level debug output. "ALL" defaults * to 0 which is off, or no debug output. * * The debug output levels are actually a bit field that controls what output is generated. * Those bit fields are described below: *
*
0x1
High level debug prints (these debug printfs are not common)
*
0x2
Normal debug prints (these debug printfs are common)
*
0x4
Function call tracing (these debug printfs are used sporadically)
*
0x8
Data dump (really only used in the "SOCKET" module - can generate a * lot of output)
*
* * Typically, when enabling debug for a subsystem, the level would be set to 7 which enables * High level debug, normal debug, and function call tracing. Setting the level 0, forces * debug output to be off for the specified subsystem. * * @param {String} _module name of the module to generate debug output * @param {Number} level debug level to set for the module * @param {statusCallback} callback the statusCallback will contain: * BUS_NO_SUCH_OBJECT if daemon was not built in debug mode. */ this.setDaemonDebug = function(_module, level, callback) {}; /** * Set the expiration time on keys associated with a specific remote peer as * identified by its peer GUID. * * The peer GUID associated with a bus name can be obtained by calling * getPeerGUID. If the timeout is 0 this is equivalent to calling clearKeys. * * @param {String} guid the GUID of a remote authenticated peer * @param {Number} timeout the time in seconds relative to the current time to expire the * keys (range 0 to 4,294,967,295) * @param {statusCallback} callback status the statusCallback will contain: * OK if the expiration time was successfully set. * UNKNOWN_GUID if there is no authenticated peer with the specified GUID. * Other error status codes indicating a failure. */ this.setKeyExpiration = function(guid, timeout, callback) {}; /** * Set the link timeout for a session. * * Link timeout is the maximum number of seconds that an unresponsive * daemon-to-daemon connection will be monitored before declaring the session lost * (via the SessionLostListener onLost callback). Link timeout defaults to 0 which * indicates that AllJoyn link monitoring is disabled. * * Each transport type defines a lower bound on link timeout to avoid defeating * transport specific power management algorithms. * * @param {SessionId} id ID of session whose link timeout will be modified * @param {Number} linkTimeout max number of seconds that a link can be unresponsive before * being declared lost. 0 indicates that AllJoyn link monitoring * will be disabled. (range 0 to 4,294,967,295) * @param {linkTimeoutCallback} callback callback that indicates the resulting (possibly upward) adjusted * linkTimeout value that acceptable to the underlying transport */ this.setLinkTimeout = function(id, linkTimeout, callback) {}; /** * Sets the session listener for an existing session ID. * * Calling this operation will override the listener set by a previous call to * setSessionListener or any listener specified in JoinSession. * * The listener is supplied as a named-parameter object literal. *
*
onLost
*
a SessionLostListener called by the bus * when an existing session becomes disconnected
*
onMemberAdded
*
a SessionMemberAddedListener called * by the bus when a member of a multipoint session is added
*
onMemberRemoved
*
a SessionMemberRemovedListener called * by the bus when a member of a multipoint session is removed
*
* * @param {SessionId} id the session id of an existing session * @param {object} listener the listener to associate with the session; see above. May be * null to clear the previous listener. * @param {statusCallback} callback contains OK if call to setSessionListener was successfull. */ this.setSessionListener = function(id, listener, cb){}; /** * Cancels an existing port binding. * * @param {SessionPort} port existing session port to be un-bound * @param {sessionCallback} callback The sessionCallback contains: * BUS_NOT_CONNECTED if a connection has not been made with a local bus. * Other error status codes indicating a failure. */ this.unbindSessionPort = function(port, callback){}; /** * Unregisters an object that was previously registered with addBusListener. * * @param {BusListener} listener the object instance to unregister as a listener * @param {statusCallback} callback indicates function that will be run once unregisterBusListener * method has completed. */ this.unregisterBusListener = function(listener, callback){}; /** * Unregisters a locally located DBus object. * * @param {String} objectPath the absolute object path of the DBus object * @param {statusCallback} callback callback function that should be run once the BusObject has * been unregistered. */ this.unregisterBusObject = function(objectPath, callback) {}; /** * Unregisters a signal handler. * * This must be called with the identical parameters supplied to registerSignalHandler. * * @param {MessageListener} signalListener the function called when the signal is received * @param {String} signalName the interface and member of the signal of the form * "org.sample.Foo.Echoed" where "org.sample.Foo" is * the interface and "Echoed" is the member * @param {String} [sourcePath] the optional object path of the emitter of the signal * @param {statusCallback} callback statusCallback with contain: * OK if request was successful * BUS_NOT_CONNECTED if a connection has not been made with a local bus. * other error status codes indicating a failure. */ this.unregisterSignalHandler= function(signalListener, signalName, sourcePath, callback) {}; }; //Documentation for the different types of callback functions /** * callback function containing a status code * * When the previous method call was successful status will be undefined or null * * @callback statusCallback * @param {Status} status AllJoyn status code */ var statusCallback = function(status) {}; /** * callback function containing the status code and SessionPort number * * @callback sessionPortCallback * @param {Status} status AllJoyn status code * @param {Number} port The sessionPort assigned as a result of the bindSessionPort method call. (range 0 to 65,535) */ var sessionPortCallback = function(status, port) {}; /** * callback function containing the status code and the InterfaceDescription * * @callback interfaceDescriptionCallback * @param {Status} status AllJoyn status code * @param {InterfaceDescription} interfaceDescription an AllJoyn InterfaceDescription */ var interfaceDescriptionCallback = function(status, interfaceDescription) {}; /** * callback function containing the status code and a collection of InterfaceDescritptions * * @callback interfaceDescriptionsCallback * @param {Status} status AllJoyn status code * @param {InterfaceDescription[]} interfaceDescriptions an array of interfaceDescriptions * @param {Number} numIfaces the number of interfaces in the interfaceDescriptions param. */ var interfaceDescriptionsCallback = function(status, interfaceDescriptions, numIfaces) {}; /** * callback function containing the time in seconds relative to the current time when the keys will expire * * @callback timeoutCallback * @param {Status} status AllJoyn status code * @param {Number} timeout The time in seconds relative to the current time when the keys will expire */ var timeoutCallback = function(status, timeout) {}; /** * callback function containing the guid for the local or remote peer * * @callback guidCallback * @param {Status} status AllJoyn status code * @param {String} guid the guid string for the local or remote peer */ var guidCallback = function(status, guid) {}; /** * true if peer security has been enabled, false otherwise. * * @callback securityEnabledCallback * @param {Status} status AllJoyn status code * @param {Boolean} enabled true if peer security has been enabled, false otherwise. */ var securityEnabledCallback = function(status, enabled) {}; /** * callback function containing status code and proxyBusObject * * @callback proxyBusObjectCallback * @param {Status} status AllJoyn status code * @param {ProxyBusObject} proxyBusObject the requested ProxyBusObject */ var proxyBusObjectCallback = function(status, proxyBusObject) {}; /** * callback function containing the current timestamp in milliseconds * * @callback timestampCallback * @param {Status} status AllJoyn status code * @param {Number} timestamp The current timestamp in milliseconds */ var timestampCallback = function(status, timestamp) {}; /** * callback function containing the socket file descriptor for a session * * @callback socketFdCallback * @param {Status} status AllJoyn status code * @param {SocketFd} socketFd socket fild descriptor for a session */ var socketFdCallback = function(status, socketFd) {}; /** * callback function indicating if name ownership was able to be determined * * @callback hasOwnerCallback * @param {Status} status AllJoyn status code * @param {Boolean} hasOwner true if name exists on the bus. if status is not OK the hasOwner * parameter is not modified. */ var hasOwnerCallback = function(status, hasOwner) {}; /** * callback function indicating the number of second that a link can be unresponcive * * @callback linkTimeoutCallback * @param {Status} status AllJoyn status code: * OK if successful * ALLJOYN_SETLINKTIMEOUT_REPLY_NOT_SUPPORTED if local daemon does not support SetLinkTimeout * ALLJOYN_SETLINKTIMEOUT_REPLY_NO_DEST_SUPPORT if SetLinkTimeout not supported by destination * BUS_NO_SESSION if the Session id is not valid * ALLJOYN_SETLINKTIMEOUT_REPLY_FAILED if SetLinkTimeout failed * BUS_NOT_CONNECTED if the BusAttachment is not connected to the daemon * @param {Number} linkTimeout this value will be the resulting (possibly upward) adjusted linkTimeout value that is acceptable to the underlying transport. */ var linkTimeoutCallback = function(status, linkTimeout) {}; alljoyn-15.09a+dfsg.1/alljoyn_js/docs/SConscript0000644000175000017500000000264312620747066020772 0ustar debiandebian# Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # import os import difflib Import('env') jsdocenv = env.Clone() vars = Variables() vars.Add(PathVariable('JSDOC_DIR', 'The path to the JsDoc toolkit', os.environ.get('JSDOC_DIR'), PathVariable.PathIsDir)) vars.Update(jsdocenv) Help(vars.GenerateHelpText(jsdocenv)) if jsdocenv.has_key('JSDOC_DIR'): jsdocenv.PrependENVPath('PATH', jsdocenv.get('JSDOC_DIR')) # Build docs if jsdocenv.has_key('JSDOC_DIR'): jsdocenv['JSDOC_TEMPLATE'] = jsdocenv.Dir('$JSDOC_DIR/templates/default') doc_out = jsdocenv.jsdoc3(target=[jsdocenv.Dir('html')], source=['alljoyn_doc']) documentation = jsdocenv.Install('$JS_DISTDIR/docs', 'html') alljoyn-15.09a+dfsg.1/alljoyn_js/jsTestDriver-npapi.conf0000644000175000017500000000355012620747066022432 0ustar debiandebian# Copyright AllSeen Alliance. All rights reserved. # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # server: http://localhost:4224 load: # # Test prerequisites # - js/npapi/alljoyn_init.js - test/common.js - test/requestPermission.js # # Core tests # - test/AboutListenerTest.js - test/AboutProxyTest.js - test/AboutObjTest.js - test/AuthListenerTest.js - test/BusAttachmentArgCountTest.js - test/BusAttachmentTest.js - test/BusAttachmentHelpersTest.js - test/BusErrorTest.js - test/BusListenerTest.js - test/BusObjectTest.js - test/ConstantsTest.js - test/KeyStoreTest.js - test/InterfaceDescriptionTest.js - test/MarshalTest.js - test/MessageArgCountTest.js - test/MessageTest.js - test/ObjSecurityTest.js - test/ProxyBusObjectArgCountTest.js - test/ProxyBusObjectTest.js - test/ProxyMethodArgCountTest.js - test/ProxyMethodTest.js - test/ProxyInterfaceTest.js - test/SessionTest.js - test/SocketFdArgCountTest.js # disabled for the time being: - test/SocketFdTest.js - test/VersionTest.js # # Basic application tests # - test/AddressBookTest.js - test/GameTest.js - test/PropsTest.js - test/SimpleTest.js alljoyn-15.09a+dfsg.1/alljoyn_js/.gitignore0000644000175000017500000000016612620747066020016 0ustar debiandebianbuild *~ docs/html .sconsign.dblite jni/*.o jni/os/*/*.o jni/*.so *.o docs/alljoyn.wxml bin gen *.class whitespace.db alljoyn-15.09a+dfsg.1/alljoyn_js/.project0000644000175000017500000000146012620747066017473 0ustar debiandebian AllJoynPlugin com.android.ide.eclipse.adt.ResourceManagerBuilder com.android.ide.eclipse.adt.PreCompilerBuilder org.eclipse.jdt.core.javabuilder com.android.ide.eclipse.adt.ApkBuilder com.android.ide.eclipse.adt.AndroidNature org.eclipse.jdt.core.javanature alljoyn-15.09a+dfsg.1/alljoyn_js/AndroidManifest.xml0000644000175000017500000000260512620747066021617 0ustar debiandebian alljoyn-15.09a+dfsg.1/alljoyn_js/samples/0000755000175000017500000000000012620747066017467 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/0000755000175000017500000000000012620747066020632 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/0000755000175000017500000000000012620747066022110 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/js/0000755000175000017500000000000012620747066022524 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/js/client.js0000644000175000017500000000335512620747066024346 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var onDeviceReady = function() { var $ = function(id) { return document.getElementById(id); }; var stringProp = $('stringProp'), intProp = $('intProp'); stringProp.onkeypress = function(event) { var c = event.which ? event.which : event.keyCode; if (c === 13) { alljoyn.setStringProp(stringProp.value); return false; } }; intProp.onkeypress = function(event) { var c = event.which ? event.which : event.keyCode; if (c === 13) { alljoyn.setIntProp(intProp.value); return false; } }; alljoyn.onstringprop = function(value) { stringProp.placeholder = value; }; alljoyn.onintprop = function(value) { intProp.placeholder = value; }; alljoyn.start(); }; if (window.cordova) { document.addEventListener('deviceready', onDeviceReady, false); } else { onDeviceReady(); } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/js/alljoyn.js0000644000175000017500000001304112620747066024531 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var alljoyn = (function() { var that, bus, proxyObj; var start = function() { bus = new org.alljoyn.bus.BusAttachment(); var connect = function(err) { bus.connect(getProxyBusObject); }; var getProxyBusObject = function(err) { if (err) { alert("Connect to AllJoyn failed [(" + err + ")]"); return; } bus.getProxyBusObject("org.alljoyn.bus.samples.props/testProperties", getAll); }; /* * Property Get, Set, and GetAll methods are part of the org.freedesktop.DBus.Properties * interface implemented by all objects containing properties. The methods take the * property name and the interface name it is a part of as parameters. */ var getAll = function(err, proxyBusObject) { proxyObj = proxyBusObject; that.getAll(); }; bus.create(true, connect); }; that = {}; that.start = function() { navigator.requestPermission("org.alljoyn.bus", function() { start(); }); } that.getStringProp = function() { var onGet = function(err, context, value) { if (err) { alert("Get 'StringProp' failed " + err); return; } /* * The method returnSignature of org.freedesktop.DBus.Properties.Get is "v", an * AllJoyn VARIANT. Incoming variants strip the outermost variant wrapper of their * value. So you see value used directly instead of value.s. */ that.onstringprop(value); }; /* * Get the "StringProp" property of the "org.alljoyn.bus.samples.props.PropsInterface" * interface of the remote object. */ proxyObj.methodCall("org.freedesktop.DBus.Properties", "Get", "org.alljoyn.bus.samples.props.PropsInterface", "StringProp", onGet); }; that.setStringProp = function(value) { var onSet = function(err, context) { if (err) { alert("Set 'StringProp' failed " + err); } that.onstringprop(value); }; /* * Set the "StringProp" property of the "org.alljoyn.bus.samples.props.PropsInterface" * interface of the remote object. The method signature of * org.freedesktop.DBus.Properties.Set is "v", an AllJoyn VARIANT. Outgoing variants * must specify the signature of their value, so you see { "s": value } passed as the * argument to Set to indicate a STRING value. */ proxyObj.methodCall("org.freedesktop.DBus.Properties", "Set", "org.alljoyn.bus.samples.props.PropsInterface", "StringProp", { "s": value }, onSet); }; that.getIntProp = function() { var onGet = function(err, context, value) { if (err) { alert("Get 'IntProp' failed " + err); } that.onintprop(value); }; proxyObj.methodCall("org.freedesktop.DBus.Properties", "Get", "org.alljoyn.bus.samples.props.PropsInterface", "IntProp", onGet); }; that.setIntProp = function(value) { var onSet = function(err, context) { if (err) { alert("Get 'IntProp' failed " + err); } that.onintprop(value); }; proxyObj.methodCall("org.freedesktop.DBus.Properties", "Set", "org.alljoyn.bus.samples.props.PropsInterface", "IntProp", { "i": value }, onSet); }; that.getAll = function() { var onGet = function(err, context, values) { if (err) { alert("Get all properties failed " + err); } /* * The method returnSignature of org.freedesktop.DBus.Properties.GetAll is "a{sv}", * an array of string to variant DICT_ENTRYs. Incoming variants strip the outermost * variant wrapper of their value, so you see values.StringProp used directly * instead of values.StringProp.s (similarly values.IntProp instead of * values.IntProp.i). */ that.onstringprop(values.StringProp); that.onintprop(values.IntProp); }; proxyObj.methodCall("org.freedesktop.DBus.Properties", "GetAll", "org.alljoyn.bus.samples.props.PropsInterface", onGet); }; return that; }()); alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/css/0000755000175000017500000000000012620747066022700 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/css/style.css0000644000175000017500000000227712620747066024562 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ object.hidden { visibility: hidden !important; width: 0px !important; height: 0px !important; margin: 0px !important; padding: 0px !important; border-style: none !important; border-width: 0px !important; max-width: 0px !important; max-height: 0px !important; } label { float: left; width: 5em; } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/client/index.html0000644000175000017500000000272612620747066024114 0ustar debiandebian Properties Client

alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/0000755000175000017500000000000012620747066022272 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/js/0000755000175000017500000000000012620747066022706 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/js/service.js0000644000175000017500000000245512620747066024712 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var onDeviceReady = function() { var $ = function(id) { return document.getElementById(id); }; var stringProp = $('stringProp'), intProp = $('intProp'); alljoyn.onstringprop = function(value) { stringProp.innerHTML = value; }; alljoyn.onintprop = function(value) { intProp.innerHTML = value; }; alljoyn.start(); }; if (window.cordova) { document.addEventListener('deviceready', onDeviceReady, false); } else { onDeviceReady(); } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/js/alljoyn.js0000644000175000017500000000771012620747066024721 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var alljoyn = (function() { var NAME = "org.alljoyn.bus.samples.props", OBJECT_PATH = "/testProperties"; var that, bus, busObject; var start = function() { bus = new org.alljoyn.bus.BusAttachment(); var connect = function(err) { bus.connect(createInterface); }; var createInterface = function(err) { if (err) { alert("Connect to AllJoyn failed [(" + err + ")]"); return; } bus.createInterface({ name: "org.alljoyn.bus.samples.props.PropsInterface", /* * Specify two properties of this interface, a string property and an integer * property. Both properties can be got and set. */ property: [ { name: "StringProp", signature: "s", access: "readwrite" }, { name: "IntProp", signature: "i", access: "readwrite" } ] }, registerBusObject); }; var registerBusObject = function(err) { busObject = (function() { var stringProp = "Hello"; var intProp = 6; /* * An implementation of PropsInterface. Property get and set implementations * are implemented as JavaScript getters and setters. The JavaScript name of * the property is identical to the name specified in the AllJoyn interface. */ return { "org.alljoyn.bus.samples.props.PropsInterface": { get StringProp() { return stringProp; }, set StringProp(value) { stringProp = value; that.onstringprop(stringProp); }, get IntProp() { return intProp; }, set IntProp(value) { intProp = value; that.onintprop(intProp); } } }; }()); bus.registerBusObject(OBJECT_PATH, busObject, requestName); }; var requestName = function(err) { bus.requestName(NAME, done); }; var done = function(err) { if (err) { alert("Request name '" + NAME + "' failed [(" + err + ")]"); return; } that.onstringprop(busObject["org.alljoyn.bus.samples.props.PropsInterface"].StringProp); that.onintprop(busObject["org.alljoyn.bus.samples.props.PropsInterface"].IntProp); }; bus.create(true, connect); }; that = {}; that.start = function() { navigator.requestPermission("org.alljoyn.bus", function() { start(); }); } return that; }()); alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/css/0000755000175000017500000000000012620747066023062 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/css/style.css0000644000175000017500000000226712620747066024743 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ object.hidden { visibility: hidden !important; width: 0px !important; height: 0px !important; margin: 0px !important; padding: 0px !important; border-style: none !important; border-width: 0px !important; max-width: 0px !important; max-height: 0px !important; } .value { font-style: italic; } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/props/service/index.html0000644000175000017500000000302712620747066024271 0ustar debiandebian Properties Service
NameValue
StringProp
IntProp
alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/0000755000175000017500000000000012620747066020760 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/simple.js0000644000175000017500000000545712620747066022622 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var $ = function(id) { return document.getElementById(id); }; var log = $('log'); var onKeyPress = function(event) { var c = event.which ? event.which : event.keyCode, message; if (c === 13) { message = document.forms['message']; client.ping(message.text.value); message.reset(); return false; } }; /* * The chat log fills the remainder of the vertical height. */ var resizeLog = function() { var innerHeight = window.innerHeight, offsetHeight = log.offsetParent.offsetHeight, scrollHeight = log.offsetParent.scrollHeight, delta = scrollHeight - offsetHeight; log.style.maxHeight = innerHeight - log.offsetTop - delta; }; window.onload = resizeLog; window.onresize = resizeLog; var logLine = function(line) { log.appendChild(line); /* Scroll the log if needed to show the most recent message at the bottom. */ log.scrollTop = log.scrollHeight - log.clientHeight; }; var logPing = function(sender, message) { var li, timestamp, name, text; li = document.createElement('li'); timestamp = document.createElement('span'); timestamp.className = 'timestamp'; timestamp.innerHTML = '[' + new Date().toLocaleTimeString() + '] '; li.appendChild(timestamp); name = document.createElement('span'); name.className = 'sender'; name.innerHTML = '(' + sender + ') '; li.appendChild(name); text = document.createElement('span'); text.className = 'text'; text.innerHTML = message; li.appendChild(text); logLine(li); }; var logStatus = function(message) { var li, timestamp, text; li = document.createElement('li'); timestamp = document.createElement('span'); timestamp.className = 'timestamp'; timestamp.innerHTML = '[' + new Date().toLocaleTimeString() + '] '; li.appendChild(timestamp); text = document.createElement('span'); text.className = 'text'; text.innerHTML = message; li.appendChild(text); logLine(li); }; alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/0000755000175000017500000000000012620747066022236 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/js/0000755000175000017500000000000012620747066022652 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/js/client.js0000644000175000017500000000204612620747066024470 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var onDeviceReady = function() { client.onping = logPing; client.onstatus = logStatus; client.start(); }; if (window.cordova) { document.addEventListener('deviceready', onDeviceReady, false); } else { onDeviceReady(); } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/js/alljoyn.js0000644000175000017500000001647712620747066024677 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var client = (function() { var SERVICE_NAME = "org.alljoyn.bus.samples.simple", CONTACT_PORT = 42; var that, bus, sessionId, isConnected = false, isStoppingDiscovery = false; var start = function() { /* * All communication through AllJoyn begins with a BusAttachment. * * By default AllJoyn does not allow communication between devices (i.e. bus to bus * communication). The optional first argument must be set to true to allow * communication between devices. */ bus = new org.alljoyn.bus.BusAttachment(); /* * Register a bus listener to receive advertised names. We look for a specific * advertised name below (the well-known SERVICE_NAME). */ var registerBusListener = function(err) { bus.registerBusListener({ onFoundAdvertisedName: function(name, transport, namePrefix) { /* * We found someone advertising the well-known SERVICE_NAME. Now join a * session of that someone. */ /* * If discovery is currently being stopped we won't join to any other * sessions. */ if (isStoppingDiscovery) { return; } /* * In order to join the session, we need to provide the well-known contact * port. This is pre-arranged between both sides as part of the definition * of the simple service. */ var onJoined = function(err, id, opts) { if (err) { alert("Join session '" + name + "' failed [(" + err + ")]"); return; } /* * As a result of joining the session, we get a session identifier which * we must use to identify the created session communication channel * whenever we talk to the remote side. * * Save the session identifier until we try to talk to the remote side. */ sessionId = id; isConnected = true; that.onstatus("Session '" + id + "' joined"); }; bus.joinSession({ host: name, port: CONTACT_PORT, onLost: function(id, reason) { that.onstatus("Session '" + id + "' lost (reason " + reason + ")"); } }, onJoined); } }, connect); }; /* To communicate with AllJoyn objects, we must connect the BusAttachment to the bus. */ var connect = function(err) { if (err) { alert("Register bus listener failed [(" + err + ")]"); return; } bus.connect(findAdvertisedName); }; /* * Now find an instance of the AllJoyn object we want to call. We start by looking for * a name, then join a session of the device that is advertising that name. * * In this case, we are looking for the well-known SERVICE_NAME. */ var findAdvertisedName = function(err) { if (err) { alert("Connect failed [(" + err + ")]"); return; } bus.findAdvertisedName(SERVICE_NAME, done); }; var done = function(err) { if (err) { alert("Find advertised name failed [(" + err + ")]"); return; } }; bus.create(true, registerBusListener); }; that = {}; that.start = function() { /* The user must allow the page to access AllJoyn. */ navigator.requestPermission("org.alljoyn.bus", function() { start(); }); } that.stop = function() { /* Release all resources acquired in the start. */ var disconnect = function(err) { if (err) { alert("Leave session failed [(" + err + ")]"); } bus.disconnect(done); }; var done = function(err) { if (err) { alert("Disconnect failed [(" + err + ")]"); } bus.destroy(); }; isStoppingDiscovery = true; if (isConnected) { bus.leaveSession(sessionId, disconnect); } else { disconnect(); } }; /* * Call the service's Ping method through a ProxyBusObject. * * This will also log the string that was sent to the service and the string that was * received from the service to the user interface. */ that.ping = function(str) { /* * To communicate with an AllJoyn object, we create a ProxyBusObject. A ProxyBusObject * is composed of a name, path, and sessionID. * * This ProxyBusObject is located at the well-known SERVICE_NAME, under path * "/SimpleService", and uses the sessionID we received earlier when we joined the * session. */ var ping = function(err, proxyObj) { /* Make the Ping method call on the simpleInterface proxy object's interface. */ that.onping("Me", str); proxyObj.methodCall("org.alljoyn.bus.samples.simple.SimpleInterface", "Ping", str, function(err, context, str) { if (err) { that.onstatus("Ping failed " + error); return; } that.onping(context.sender, str); }); }; bus.getProxyBusObject(SERVICE_NAME + "/SimpleService:sessionId=" + sessionId, ping); }; return that; }()); alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/css/0000755000175000017500000000000012620747066023026 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/css/style.css0000644000175000017500000000253612620747066024706 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ object.hidden { visibility: hidden !important; width: 0px !important; height: 0px !important; margin: 0px !important; padding: 0px !important; border-style: none !important; border-width: 0px !important; max-width: 0px !important; max-height: 0px !important; } ol { background: #ccc; list-style-type: none; overflow: auto; padding-left: 0px; margin: 0px; } ol li { border-top: 1px solid #ddd; } ol li:first-child { border-top: none; } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/client/index.html0000644000175000017500000000332612620747066024237 0ustar debiandebian Simple Client
alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/0000755000175000017500000000000012620747066022420 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/js/0000755000175000017500000000000012620747066023034 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/js/service.js0000644000175000017500000000205112620747066025030 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var onDeviceReady = function() { service.onping = logPing; service.onstatus = logStatus; service.start(); }; if (window.cordova) { document.addEventListener('deviceready', onDeviceReady, false); } else { onDeviceReady(); } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/js/alljoyn.js0000644000175000017500000001504412620747066025046 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var service = (function() { var SERVICE_NAME = "org.alljoyn.bus.samples.simple", CONTACT_PORT = 42; var that, aj, bus; aj = org.alljoyn.bus; var start = function() { /* * All communication through AllJoyn begins with a BusAttachment. * * By default AllJoyn does not allow communication between devices (i.e. bus to bus * communication). The optional first argument must be set to true to allow * communication between devices. */ bus = new aj.BusAttachment(); /* * Specify an AllJoyn interface. The name by which this interface will be known is the * property name of the bus.interfaces object. In this case, it is * "org.alljoyn.bus.samples.simple.SimpleInterface". */ var createInterface = function(err) { bus.createInterface({ name: "org.alljoyn.bus.samples.simple.SimpleInterface", /* * Specify a Ping method of the interface. The input argument and return value are * both strings. */ method: [ { name: "Ping", signature: "s", returnSignature: "s", argNames: "inStr,outStr" } ] }, registerBusObject); }; /* * To make a service available to other AllJoyn peers, register a BusObject with the * BusAttachment at a specific path. * * Our service is an object located at the "/SimpleService" path. */ var registerBusObject = function(err) { bus.registerBusObject("/SimpleService", { /* * Our service implements the org.alljoyn.bus.samples.simple.SimpleInterface * interface. */ "org.alljoyn.bus.samples.simple.SimpleInterface": { /* * This function is called when a remote attachment makes a method call on this * bus object. All method handler functions are called with a message context * followed by the method arguments. * * Returning a value from the method is done by calling the reply method of the * context. */ Ping: function(context, str) { that.onping(context.sender, str); /* Echo the input argument back as the method return value. */ context.reply(str); that.onping(bus.uniqueName, str); } } }, connect); }; /* * The next steps in making a service available to other AllJoyn peers is to connect the * BusAttachment to the bus, bind a session port, and obtain a well-known name. */ var connect = function(err) { /* Connect the BusAttachment to the bus. */ bus.connect(bindSessionPort); }; /* Create a new session listening on the contact port of the simple service. */ var bindSessionPort = function(err) { if (err) { alert("Connect to AllJoyn failed [(" + err + ")]"); return; } bus.bindSessionPort({ port: CONTACT_PORT, onAccept: function(port, joiner, opts) { return (port === CONTACT_PORT); }, onJoined: function(port, id, joiner) { that.onstatus("(" + joiner + ") joined session '" + id + "'"); } }, requestName); }; /* Request a well-known name from the bus... */ var requestName = function(err) { if (err) { alert("Bind session port failed [(" + err + ")]"); return; } bus.requestName(SERVICE_NAME, aj.BusAttachment.DBUS_NAME_FLAG_REPLACE_EXISTING | aj.BusAttachment.DBUS_NAME_FLAG_DO_NOT_QUEUE, advertiseName); }; /* ...and advertise the same well-known name. */ var advertiseName = function(err) { if (err) { alert("Request '" + SERVICE_NAME + "' failed [(" + err + ")]"); return; } bus.advertiseName(SERVICE_NAME, aj.SessionOpts.TRANSPORT_ANY, done); }; var done = function(err) { if (err) { alert("Advertise '" + SERVICE_NAME + "' failed [(" + err + ")]"); return; } }; bus.create(true, createInterface); }; that = {}; that.start = function() { navigator.requestPermission("org.alljoyn.bus", function() { start(); }); } /* Release all resources acquired in start. */ that.stop = function() { var disconnect = function(err) { bus.disconnect(done); }; var done = function(err) { if (err) { alert("Disconnect from AllJoyn failed [(" + err + ")]"); } bus.destroy(); }; bus.unregisterBusObject("/SimpleService", disconnect); }; return that; }()); alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/css/0000755000175000017500000000000012620747066023210 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/css/style.css0000644000175000017500000000253612620747066025070 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ object.hidden { visibility: hidden !important; width: 0px !important; height: 0px !important; margin: 0px !important; padding: 0px !important; border-style: none !important; border-width: 0px !important; max-width: 0px !important; max-height: 0px !important; } ol { background: #ccc; list-style-type: none; overflow: auto; padding-left: 0px; margin: 0px; } ol li { border-top: 1px solid #ddd; } ol li:first-child { border-top: none; } alljoyn-15.09a+dfsg.1/alljoyn_js/samples/simple/service/index.html0000644000175000017500000000263512620747066024423 0ustar debiandebian Simple Service
alljoyn-15.09a+dfsg.1/alljoyn_js/samples/about/0000755000175000017500000000000012620747066020601 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/about/client/0000755000175000017500000000000012620747066022057 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/about/client/js/0000755000175000017500000000000012620747066022473 5ustar debiandebianalljoyn-15.09a+dfsg.1/alljoyn_js/samples/about/client/js/alljoyn_init.js0000644000175000017500000000735212620747066025533 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ (function() { var bus = null, permissionLevel, requestPermission, found, i; /* * Check if AllJoyn is already initialized. */ if (window.org && window.org.alljoyn) { return; } if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes['application/x-alljoyn']) { /* * Create an object element that will load the AllJoyn plugin. */ bus = document.createElement('object'); bus.type = 'application/x-alljoyn'; /* * Hide the element. It's necessary to use the method below instead of changing the * visibility to ensure that the plugin has a top-level window for the permission request * dialog. */ bus.style.position = 'absolute'; bus.style.left = 0; bus.style.top = -500; bus.style.width = 1; bus.style.height = 1; bus.style.overflow = 'hidden'; document.documentElement.appendChild(bus); /* * Check that everything was loaded correctly. */ if (bus && (typeof bus.BusAttachment === 'undefined')) { bus = null; } } if (!bus) { return; } /* * Put the AllJoyn namespace object in the right place. */ if (!window.org) { org = {}; } if (!window.org.alljoyn) { window.org.alljoyn = {bus: bus}; } /* * Until the feature permissions API is supported and available to the plugin, use the fallback * implementation in the plugin. */ if (!window.navigator.USER_ALLOWED) { window.navigator.USER_ALLOWED = bus.USER_ALLOWED; window.navigator.DEFAULT_ALLOWED = bus.DEFAULT_ALLOWED; window.navigator.DEFAULT_DENIED = bus.DEFAULT_DENIED; window.navigator.USER_DENIED = bus.USER_DENIED; } permissionLevel = window.navigator.permissionLevel; window.navigator.permissionLevel = function(feature) { if (feature === 'org.alljoyn.bus') { return bus.permissionLevel(feature); } else { return permissionLevel(feature); } } requestPermission = window.navigator.requestPermission; window.navigator.requestPermission = function(feature, callback) { if (feature === 'org.alljoyn.bus') { return bus.requestPermission(feature, callback); } else { return requestPermission(feature, callback); } } found = false; for (i = 0; window.navigator.privilegedFeatures && (i < window.navigator.privilegedFeatures.length); ++i) { if (window.navigator.privilegedFeatures[i] === 'org.alljoyn.bus') { found = true; } } if (!found) { if (window.navigator.privilegedFeatures) { window.navigator.privilegedFeatures.push('org.alljoyn.bus'); } else { window.navigator.privilegedFeatures = bus.privilegedFeatures; } } })(); alljoyn-15.09a+dfsg.1/alljoyn_js/samples/about/client/js/alljoyn.js0000644000175000017500000003271312620747066024507 0ustar debiandebian/* * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ var alljoyn = (function() { var DEVICES = []; DEVICES.displayingIndex = -1; // About global variable var ABOUT = []; /* * interface name for whoImplements */ ABOUT.interfaces = ["*"]; /* * org.alljoyn.About interface definitions */ ABOUT.INTERFACE_NAME = "org.alljoyn.About"; /* * org.alljoyn.About.Icon interface definitions */ ABOUT.ICON_OBJECT_PATH = "/About/DeviceIcon"; ABOUT.ICON_INTERFACE_NAME = "org.alljoyn.Icon"; /* * handler for the org.alljoyn.About.Anounce sessionless signal * @param[in] busName well know name of the remote BusAttachment * @param[in] version version of the Announce signal from the remote About Object * @param[in] port SessionPort used by the announcer * @param[in] objectDescriptionArg MsgArg the list of object paths and interfaces in the announcement * @param[in] aboutDataArg MsgArg containing a dictionary of Key/Value pairs of the AboutData */ ABOUT.announceListener = { onAnnounced : function(busName, version, port, objectDescriptionArg, aboutDataArg) { console.log("=========================================="); console.log("busName : " + busName + ", version : " + version + ", port : " + port); var objectDescStr = ""; for (var path in objectDescriptionArg) { objectDescStr += objectDescriptionArg[path][0]; objectDescStr += ', '; for (var intf in objectDescriptionArg[path][1]) { objectDescStr += objectDescriptionArg[path][1][intf]; } objectDescStr += '\n'; } console.log(objectDescStr); var hasIcon = hasAboutIcon(objectDescriptionArg); console.log("hasIcon : " + hasIcon); if (hasIcon) { joinForGetIcon(busName, port); } var aboutDataStr = ""; for (var key in aboutDataArg) { aboutDataStr += key + " = " + aboutDataArg[key] + '\n'; } console.log(aboutDataStr); console.log("=========================================="); DEVICES.push({ busName : busName, version : version, port : port, objectDescription : objectDescriptionArg, aboutData : aboutDataArg, imgIcon : "img/default_devices_icon.png", sessionId : -1 }); ondraw(); } } var that = [], bus; /* * Get the instance of our plugin. All our scripting will begin with this. */ aj = org.alljoyn.bus; var drawSelectedDevice = function(index) { var wrapper = document.getElementById('selected_device'); var str = ''; wrapper.innerHTML = str; } var ondraw = function() { var images = document.getElementById('main_section'); if (DEVICES.displayingIndex > -1) { drawSelectedDevice(DEVICES.displayingIndex + 1); } var str = ""; for (var i = 0; i < DEVICES.length; ++i) { str += '