Example #1
0
void FBTestPluginAPI::getURLCallback(const FB::JSObjectPtr& callback, bool success,
    const FB::HeaderMap& headers, const boost::shared_array<uint8_t>& data, const size_t size) {
    FB::VariantMap outHeaders;
    for (FB::HeaderMap::const_iterator it = headers.begin(); it != headers.end(); ++it) {
        if (headers.count(it->first) > 1) {
            if (outHeaders.find(it->first) != outHeaders.end()) {
                outHeaders[it->first].cast<FB::VariantList>().push_back(it->second);
            } else {
                outHeaders[it->first] = FB::VariantList(FB::variant_list_of(it->second));
            }
        } else {
            outHeaders[it->first] = it->second;
        }
    }
    if (success) {
        std::string dstr(reinterpret_cast<const char*>(data.get()), size);
        callback->InvokeAsync("", FB::variant_list_of
            (true)
            (outHeaders)
            (dstr)
            );
    } else {
        callback->InvokeAsync("", FB::variant_list_of(false));
    }
}
FileTransferAPIPtr FileManagerAPI::copy(std::string const &sourceUrl, std::string const &targetUrl, FB::JSObjectPtr const &callback) {
	FBLOG_DEBUG("FileManagerAPI::copy", "this=" << this << "\t" << "sourceUrl=" << sourceUrl << "\t" << "targetUrl=" << targetUrl << "\t" << "callback=" << callback);
	FB::URI sourceUri(sourceUrl);
	FB::URI targetUri(targetUrl);
	if(FileManagerAPI::isHttp(sourceUri) && FileManagerAPI::isHttp(targetUri)) {
		FBLOG_DEBUG("FileManagerAPI::copy", "Can't copy two Remote resources");
		callback->InvokeAsync("", FB::variant_list_of(false)("Can't copy two Remote resources"));
		return FileTransferAPIPtr();
	}
	if(FileManagerAPI::isInternal(targetUri)) {
		FBLOG_DEBUG("FileManagerAPI::copy", "Can't copy file into Internal resources");
		callback->InvokeAsync("", FB::variant_list_of(false)("Can't copy file into Internal resources"));
		return FileTransferAPIPtr();
	}
	if(FileManagerAPI::isHttp(sourceUri) && !isSameHost(sourceUri)) {
		FBLOG_DEBUG("FileManagerAPI::copy", "Can't use different host with remote resource (XSS)");
		callback->InvokeAsync("", FB::variant_list_of(false)("Can't use different host with remote resource (XSS)"));
		return FileTransferAPIPtr();
	}
	if(FileManagerAPI::isHttp(targetUri) && !isSameHost(targetUri)) {
		FBLOG_DEBUG("FileManagerAPI::copy", "Can't use different host with remote resource (XSS)");
		callback->InvokeAsync("", FB::variant_list_of(false)("Can't use different host with remote resource (XSS)"));
		return FileTransferAPIPtr();
	}
	FileTransferAPIPtr fileTransfer = getFactory()->getFileTransfer(sourceUri, targetUri, callback);
	return fileTransfer;
}
void FileManagerAPI::exists(std::string const &url, FB::JSObjectPtr const &callback) {
	FBLOG_DEBUG("FileManagerAPI::exists", "this=" << this << "\t" << "url=" << url << "\t" << "callback=" << callback);
	FB::URI uri(url);
	if(!FileManagerAPI::isFile(uri)) {
		FBLOG_DEBUG("FileManagerAPI::exists", "Can't check Remote resource");
		callback->InvokeAsync("", FB::variant_list_of(false)("Can't check Remote resource"));
		return;
	}
	try {
		std::string pathStr = uriToFile(uri);
		if(pathStr.empty()) {
			FBLOG_DEBUG("FileManagerAPI::exists", "Invalid path");
			callback->InvokeAsync("", FB::variant_list_of(false)("Invalid path"));
			return;
		}
		boost::filesystem::path path(pathStr);
		
		FBLOG_DEBUG("FileManagerAPI::exists", "Test \"" << pathStr << "\"");
		bool b = boost::filesystem::exists(path);
		callback->InvokeAsync("", FB::variant_list_of(b)(""));
	} catch(boost::filesystem::filesystem_error &) {
		FBLOG_DEBUG("FileManagerAPI::exists", "Internal error");
		callback->InvokeAsync("", FB::variant_list_of(false)("Internal error"));
	}
}
Example #4
0
void AsinbowAPI::executeCommandWork(const std::string& command, const FB::JSObjectPtr& callback) {
    char buf[4096];
    FILE* pipe = popen(
#ifdef _WIN32
        utf8_to_ansi(command).c_str(),
#else
        command.c_str(),
#endif
        "r");
    if (!pipe) {
        callback->Invoke("", FB::variant_list_of(true)("popen failed!"));
        return;
    }
    std::string result;
    int c;
    while ((c = fgetc(pipe)) != EOF) {
        result += (char)c;
        if (c=='\n') {
#ifdef _WIN32
            result = ansi_to_utf8(result);
#endif
            callback->Invoke("", FB::variant_list_of(false)(result));
            result = "";
        }
    }
    pclose(pipe);
    callback->Invoke("", FB::variant_list_of(true));
}
Example #5
0
void GCPAPI::SetRemoteDescription(const FB::variant& action,
                                  const FB::variant& sdp,
                                  const FB::JSObjectPtr& succCb,
                                  const FB::JSObjectPtr& failCb)
{
    GoCast::RtcCenter* pCtr = GoCast::RtcCenter::Instance();
    m_onsetsdpsuccessCb = succCb;
    m_onsetsdpfailureCb = failCb;
    
    if(false == pCtr->Inited())
    {
        std::string msg = m_htmlId.convert_cast<std::string>();
        msg += ": Failed to init RtcCenter singleton...";
        FBLOG_ERROR_CUSTOM("GCPAPI::SetRemoteDescription", msg);
        
        if(NULL != failCb.get())
        {
            failCb->InvokeAsync("", FB::variant_list_of("RtcCenter init failed"));
        }
        return;
    }
    
    pCtr->SetRemoteDescription(m_htmlId.convert_cast<std::string>(),
                               m_pSetRemoteSDPObserver,
                               action.convert_cast<std::string>(),
                               sdp.convert_cast<std::string>());
}
Example #6
0
void btlauncherAPI::gotDownloadProgram(const FB::JSObjectPtr& callback, 
									   std::wstring& program,
									   std::string& version,
									   bool success,
									   const FB::HeaderMap& headers,
									   const boost::shared_array<uint8_t>& data,
									   const size_t size) {
	TCHAR temppath[500];
	DWORD gettempresult = GetTempPath(500, temppath);
	if (! gettempresult) {
		callback->InvokeAsync("", FB::variant_list_of(false)("GetTempPath")(GetLastError()));
		return;
	}
	std::wstring syspath(temppath);
	syspath.append( program.c_str() );
	boost::uuids::random_generator gen;
	boost::uuids::uuid u = gen();
	syspath.append( _T("_") );
	std::wstring wversion;
	wversion.assign( version.begin(), version.end() );
	syspath.append( wversion );
	syspath.append( _T("_") );
	syspath.append( boost::uuids::to_wstring(u) );
	syspath.append(_T(".exe"));

	HANDLE hFile = CreateFile( syspath.c_str(), GENERIC_WRITE | GENERIC_EXECUTE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, NULL, NULL );
	if (hFile == INVALID_HANDLE_VALUE) {
		
		callback->InvokeAsync("", FB::variant_list_of(false)(GetLastError()));
		return;
	}
	PVOID ptr = (VOID*) data.get();
	DWORD written = 0;
	BOOL RESULT = WriteFile( hFile, ptr, size, &written, NULL);
	CloseHandle(hFile);
	
	if (! RESULT) {
		callback->InvokeAsync("", FB::variant_list_of("FILE")(false)(GetLastError()));
		return;
	}
	std::wstring installcommand = std::wstring(syspath);
	installcommand.append(_T(" /NOINSTALL /MINIMIZED /HIDE"));
	STARTUPINFO info;
	PROCESS_INFORMATION procinfo;
	memset(&info,0,sizeof(info));
	info.cb = sizeof(STARTUPINFO);
	 
	/* CreateProcessW can modify installcommand thus we allocate needed memory */ 
	wchar_t * pwszParam = new wchar_t[installcommand.size() + 1]; 
	const wchar_t* pchrTemp = installcommand.c_str(); 
    wcscpy_s(pwszParam, installcommand.size() + 1, pchrTemp); 

	BOOL bProc = CreateProcess(NULL, pwszParam, NULL, NULL, FALSE, 0, NULL, NULL, &info, &procinfo);
	if(bProc) {
		callback->InvokeAsync("", FB::variant_list_of("PROCESS")(true)(installcommand.c_str())(GetLastError()));
	} else {
		callback->InvokeAsync("", FB::variant_list_of("PROCESS")(false)(installcommand.c_str())(GetLastError()));
	}

}
Example #7
0
long FBTestPluginAPI::countArrayLength(const FB::JSObjectPtr &jso) 
{
    if (!jso->HasProperty("getArray"))
        throw FB::invalid_arguments();
    FB::VariantList array = jso->GetProperty("getArray").cast<FB::VariantList>();
    long len = array.size();// array->GetProperty("length").convert_cast<long>();
    return len;
}
Example #8
0
int FB::BrowserHost::delayedInvoke(const int delayms, const FB::JSObjectPtr& func,
                                    const FB::VariantList& args, const std::string& fname)
{
    assertMainThread();
    FB::JSObjectPtr delegate = getDelayedInvokeDelegate();
    assert(delegate);
    if (fname.empty())
        return delegate->Invoke("", FB::variant_list_of(delayms)(func)(args)).convert_cast<int>();
    else
        return delegate->Invoke("", FB::variant_list_of(delayms)(func)(args)(fname)).convert_cast<int>();
}
Example #9
0
int FB::BrowserHost::delayedInvoke(const int delayms, const FB::JSObjectPtr& func,
                                    const FB::VariantList& args, const std::string& fname)
{
    assertMainThread();
    FB::JSObjectPtr delegate = getDelayedInvokeDelegate();
    if (!delegate)
        return -1;  // this is wrong (the return is meant to be the result of setTimeout)
    if (fname.empty())
        return delegate->Invoke("", FB::variant_list_of(delayms)(func)(args)).convert_cast<int>();
    else
        return delegate->Invoke("", FB::variant_list_of(delayms)(func)(args)(fname)).convert_cast<int>();
}
void OfficeDriveAPI::cupdateDaemon(FB::JSObjectPtr callback)
{
	/*FB::PluginEventSinkPtr eventSinkPtr;
	boost::optional<std::string> codeBase = getPlugin()->getParam("codeBase");
	std::string codeBaseUrl = "None";
	
	if (codeBase) {
		codeBaseUrl = *codeBase;
	}
	*/
	intptr_t ret = -1;
	char exePath[512];
	memset(&exePath, 0, sizeof(exePath));
	char * appData;

#ifdef FB_WIN
	appData = getenv("LOCALAPPDATA");
	sprintf(exePath, "%s\\OfficeDrive\\dist\Update.exe", appData);

	const char *localName[] = {exePath};
	char* const localArgs[] = {exePath, NULL};

	ret = _spawnv(_P_WAIT, localName[0], localArgs);
#endif

	callback->Invoke("",FB::variant_list_of(ret));

}
bool OfficeDriveAPI::callbackTest(FB::JSObjectPtr callback)
{
	callback->Invoke("", FB::variant_list_of(""));
	m_host->htmlLog("callbackTest success");
	return true;
	
}
Example #12
0
// If you override this, you probably want to call it again, since this is what calls back into the page
// to indicate that we're done.
void PluginCore::setReady()
{
    FBLOG_INFO("PluginCore", "Plugin Ready");
    // Ensure that the JSAPI object has been created, in case the browser hasn't requested it yet.
    getRootJSAPI(); 
    try {
        FB::VariantMap::iterator fnd = m_params.find("onload");
        if (fnd != m_params.end()) {
            FB::JSObjectPtr method = fnd->second.convert_cast<FB::JSObjectPtr>();
            method->InvokeAsync("", FB::variant_list_of(getRootJSAPI()));
        }
    } catch(...) {
        // Usually this would be if it isn't a JSObjectPtr or the object can't be called
    }
    onPluginReady();
}
Example #13
0
FB::variant btlauncherAPI::runProgram(const std::string& program, const FB::JSObjectPtr& callback) {
	FBLOG_INFO("runProgram()", "START");
	string exe = this->installPath;
	if (program == "SoShare")
		exe += SOSHARE_EXE_PATH;
	else if (program == "Torque")
		exe += TORQUE_EXE_PATH;
	else
		exe += BTLIVE_EXE_PATH;
		
	FBLOG_INFO("runProgram()", exe.c_str());

	struct stat st;
	if (stat(exe.c_str(), &st) == -1 || !S_ISREG(st.st_mode)) {
		FBLOG_INFO("runProgram()", "stat check problem");
		callback->InvokeAsync("", FB::variant_list_of(false)(0));
		FBLOG_INFO("runProgram()", "END");
		return 0;
	}
	
	FB::VariantList list = isRunning(program);
	if (list.empty()) {
		switch(fork()) 
		{
			case -1: {
				perror("BTLauncher Run Program Fork");
				FBLOG_INFO("runProgram()", "fork - failure");
				break;
			}
			case 0: {
				FBLOG_INFO("runProgram()", "fork - child process");
				FBLOG_INFO("runProgram()", exe.c_str());
				execlp(exe.c_str(), exe.c_str(), NULL);
				FBLOG_INFO("runProgram()", "child process exit");
				exit(1);
			}
			default: {
				break;
			}
		}
	}
	callback->InvokeAsync("", FB::variant_list_of(true)(1));
	FBLOG_INFO("runProgram()", "END");
	return 0;
}
Example #14
0
void btlauncherAPI::gotDownloadProgram(const FB::JSObjectPtr& callback, 
									   std::string& program,
									   bool success,
									   const FB::HeaderMap& headers,
									   const boost::shared_array<uint8_t>& data,
									   const size_t size) {
	FBLOG_INFO("gotDownloadProgram()", "START");
	FBLOG_INFO("gotDownloadProgram()", program.c_str());
	

	char *tmpname = strdup("/tmp/btlauncherXXXXXX");
	mkstemp(tmpname);
	ofstream f(tmpname);
	
	if (f.fail()) {
		FBLOG_INFO("gotDownloadProgram()", "f.fail");
		callback->InvokeAsync("", FB::variant_list_of(false)(-1));
		return;
	}
	f.write((char *)data.get(), size);
	f.close();
	
	std::string url;
	if (program == "SoShare")
		url = SOSHARE_DOWNLOAD_URL;
	else if (program == "Torque")
		url = TORQUE_DOWNLOAD_URL;
	else
		url = BTLIVE_DOWNLOAD_URL;
	
	FBLOG_INFO("gotDownloadProgram()", url.c_str());
	
	const char *tarFlags = "-xf";
	if (url.find(".gz") != std::string::npos)
		tarFlags = "-xzf";
	
	pid_t tarPid;
	int status;
	switch(tarPid = fork()) 
	{
		case -1:
			FBLOG_INFO("gotDownloadProgram()", "fork failed");
			break;
		case 0:
			FBLOG_INFO("gotDownloadProgram()", "running tar");
			execl("/usr/bin/tar", "tar", tarFlags, tmpname, "-C", this->installPath.c_str(), NULL);
			break;
		default:
			FBLOG_INFO("gotDownloadProgram()", "waitpid");
			waitpid(tarPid, &status, 0);
			break;
	}
	
	runProgram(program, callback);
	FBLOG_INFO("gotDownloadProgram()", "END");
}
void FB::BrowserHost::AsyncHtmlLog(void *logReq)
{
    FB::AsyncLogRequest *req = (FB::AsyncLogRequest*)logReq;
    try {
        FB::DOM::WindowPtr window = req->m_host->getDOMWindow();

        if (window->getJSObject()->HasProperty("console")) {
            FB::JSObjectPtr obj = window->getProperty<FB::JSObjectPtr>("console");
            printf("Logging: %s\n", req->m_msg.c_str());
            obj->Invoke("log", FB::variant_list_of(req->m_msg));
        }
    } catch (const std::exception &) {
        // printf("Exception: %s\n", e.what());
        // Fail silently; logging should not require success.
        FBLOG_TRACE("BrowserHost", "Logging to browser console failed");
        return;
    }
    delete req;
}
Example #16
0
FB::VariantList FBTestPluginAPI::getObjectValues(const FB::JSObjectPtr& arr)
{
    FB::VariantList outArr;
    std::map<std::string, FB::variant> inMap;
    arr->GetObjectValues(arr, inMap);

    for (std::map<std::string, FB::variant>::iterator it = inMap.begin(); it != inMap.end(); it++) {
        outArr.push_back(it->second);
    }
    return outArr;
}
Example #17
0
void btlauncherAPI::gotCheckForUpdate(const FB::JSObjectPtr& callback,
                                   bool success,
                                   const FB::HeaderMap& header,
                                   const boost::shared_array<uint8_t>& data,
                                   const size_t size) {
	FBLOG_INFO("gotCheckForUpdate()", "START");
    
	char *tmpname = strdup("/tmp/btlauncherXXXXXX.pkg");
	mkstemp(tmpname);
	ofstream f(tmpname);
	
	if (f.fail()) {
		FBLOG_INFO("gotCheckForUpdate()", "f.fail");
		callback->InvokeAsync("", FB::variant_list_of(false)(-1));
		return;
	}
	f.write((char *)data.get(), size);
	f.close();
    
    switch(fork())
    {
        case -1: {
            FBLOG_INFO("gotCheckForUpdate()", "fork - failure");
            break;
        }
        case 0: {
            FBLOG_INFO("gotCheckForUpdate()", "fork - child process");
            FBLOG_INFO("gotCheckForUpdate()", tmpname);
            execlp("installer", "installer", "-pkg", tmpname, "-target", "CurrentUserHomeDirectory", NULL);
            FBLOG_INFO("gotCheckForUpdate()", "child process exit");
            exit(1);
        }
        default: {
            FBLOG_INFO("gotCheckForUpdate()", "fork - parent process");
            break;
        }
    }
    
    callback->InvokeAsync("", FB::variant_list_of(true)(1));
	FBLOG_INFO("gotCheckForUpdate()", "END");
}
bool ProfileManager::has_user_ack(std::string profilename, FB::DOM::WindowPtr window) {
    
    try {
        if (window && window->getJSObject()->HasProperty("location")) {
            // Create a reference to the browswer console object
            FB::JSObjectPtr obj = window->getProperty<FB::JSObjectPtr>("location");
            
            std::string origin = obj->GetProperty("origin").convert_cast<std::string>();
            std::string href = obj->GetProperty("href").convert_cast<std::string>();
            
            // Return the result of authorized domain entry, if found
            std::map<std::string, bool>::iterator it = authorized_domains.find(origin);
            if (it != authorized_domains.end())
                return it->second;
            
            // Ask user
            FB::variant ack_result;
            std::stringstream ss;
            ss << "The following page requests access to the BroadMask profile ";
            ss << "'" << profilename << "' :" << endl;
            ss << href << endl << endl;
            ss << "Do you want to authorize the domain?";
            ack_result = window->getJSObject()->Invoke("confirm", FB::variant_list_of(ss.str()));
            
            bool ack = ack_result.convert_cast<bool>();
            
            if (ack == true) {
                authorized_domains.insert(std::pair<std::string, bool>(origin, true));
                return true;
            } else {
                return false;
            }
            
        }
    } catch (exception& e) {
        cerr << "[BroadMask ProfileManager] Error getting user ack: " << e.what() << endl;
        return false;
    }
    
    return false;
}
Example #19
0
FB::variant btlauncherAPI::runProgram(const std::wstring& program, const FB::JSObjectPtr& callback) {
	if (!this->isSupported(program)) {
		return _T(NOT_SUPPORTED_MESSAGE);
	}
	
	HINSTANCE ret = (HINSTANCE)0;
	if (isRunning(program).size() == 0) {
		ret = launch_program(program);
		callback->InvokeAsync("", FB::variant_list_of(false)(ret));
	}
	return ret;
}
void FileManagerAPI::mkdir(std::string const &url, FB::JSObjectPtr const &callback) {
	FBLOG_DEBUG("FileManagerAPI::mkdir", "this=" << this << "\t" << "url=" << url << "\t" << "callback=" << callback);
	FB::URI uri(url);
	try {
		if(!FileManagerAPI::isFile(uri)) {
			FBLOG_DEBUG("FileManagerAPI::mkdir", "Can't create Remote directories");
			callback->InvokeAsync("", FB::variant_list_of(false)("Can't create Remote directories"));
			return;
		}
		if(FileManagerAPI::isInternal(uri)) {
			FBLOG_DEBUG("FileManagerAPI::mkdir", "Can't create Internal directories");
			callback->InvokeAsync("", FB::variant_list_of(false)("Can't create Internal directories"));
			return;
		}
		std::string pathStr = uriToFile(uri);
		if(pathStr.empty()) {
			FBLOG_DEBUG("FileManagerAPI::mkdir", "Invalid path");
			callback->InvokeAsync("", FB::variant_list_of(false)("Invalid path"));
			return;
		}
		boost::filesystem::path path(pathStr);
		if(boost::filesystem::exists(path)) {
			FBLOG_DEBUG("FileManagerAPI::mkdir", "The path \"" << pathStr << "\" already exists");
			callback->InvokeAsync("", FB::variant_list_of(false)("Invalid file"));
			return;
		}
		
		FBLOG_DEBUG("FileManagerAPI::mkdir", "Make directories \"" << pathStr << "\"");
		boost::filesystem::create_directories(path);
		callback->InvokeAsync("", FB::variant_list_of(true)(""));
	} catch(boost::filesystem::filesystem_error &) {
		FBLOG_DEBUG("FileManagerAPI::mkdir", "Internal error");
		callback->InvokeAsync("", FB::variant_list_of(false)("Internal error"));
	}
}
void FileManagerAPI::remove(std::string const &url, FB::JSObjectPtr const &callback) {
	FBLOG_DEBUG("FileManagerAPI::remove", "this=" << this << "\t" << "url=" << url << "\t" << "callback=" << callback);
	FB::URI uri(url);
	try {
		if(!FileManagerAPI::isFile(uri)) {
			FBLOG_DEBUG("FileManagerAPI::remove", "Can't remove Remote resource");
			callback->InvokeAsync("", FB::variant_list_of(false)("Can't remove Remote resource"));
			return;
		}
		if(FileManagerAPI::isInternal(uri)) {
			FBLOG_DEBUG("FileManagerAPI::remove", "Can't remove Internal resource");
			callback->InvokeAsync("", FB::variant_list_of(false)("Can't remove Internal resource"));
			return;
		}
		std::string pathStr = uriToFile(uri);
		if(pathStr.empty()) {
			FBLOG_DEBUG("FileManagerAPI::remove", "Invalid path");
			callback->InvokeAsync("", FB::variant_list_of(false)("Invalid path"));
			return;
		}
		boost::filesystem::path path(pathStr);
		if(!boost::filesystem::exists(path)) {
			FBLOG_DEBUG("FileManagerAPI::remove", "The path \"" << pathStr << "\" doesn't exist");
			callback->InvokeAsync("", FB::variant_list_of(false)("Invalid file"));
			return;
		}
		
		FBLOG_DEBUG("FileManagerAPI::remove", "Remove \"" << pathStr << "\"");
		boost::filesystem::remove_all(path);
		callback->InvokeAsync("", FB::variant_list_of(true)(""));
	} catch(boost::filesystem::filesystem_error &) {
		FBLOG_DEBUG("FileManagerAPI::remove", "Internal error");
		callback->InvokeAsync("", FB::variant_list_of(false)("Internal error"));
	}
}
Example #22
0
void GCPAPI::GetUserMedia(const FB::JSObjectPtr& mediaHints,
                          const FB::JSObjectPtr& succCb,
                          const FB::JSObjectPtr& failCb)
{
    GoCast::RtcCenter* pCtr = GoCast::RtcCenter::Instance();
	m_htmlId = "localPlayer";
    
    if(false == pCtr->Inited())
    {
        std::string msg = m_htmlId.convert_cast<std::string>();
        msg += ": Failed to init RtcCenter singleton...";
        FBLOG_ERROR_CUSTOM("GCPAPI::GetUserMedia", msg);
        
        if(NULL != failCb.get())
        {
            failCb->InvokeAsync("", FB::variant_list_of("RtcCenter init failed"));
        }
        return;
    }
    
    pCtr->GetUserMedia(mediaHints, succCb, failCb, false);
}
Example #23
0
void btlauncherAPI::gotajax(const FB::JSObjectPtr& callback, 
							bool success,
						    const FB::HeaderMap& headers,
						    const boost::shared_array<uint8_t>& data,
						    const size_t size) {
	FBLOG_INFO("gotajax()", "START");

	FB::VariantMap response;
	response["allowed"] = true;
	response["success"] = success;
	
	if(!success) {
		FBLOG_INFO("gotajax()", "unsuccessful");
		callback->InvokeAsync("", FB::variant_list_of(response));
		FBLOG_INFO("gotajax()", "END");
		return;
	}
	
	FB::VariantMap outHeaders;
	for (FB::HeaderMap::const_iterator it = headers.begin(); it != headers.end(); ++it) {
        if (headers.count(it->first) > 1) {
            if (outHeaders.find(it->first) != outHeaders.end()) {
                outHeaders[it->first].cast<FB::VariantList>().push_back(it->second);
            } else {
                outHeaders[it->first] = FB::VariantList(FB::variant_list_of(it->second));
            }
        } else {
            outHeaders[it->first] = it->second;
        }
    }
	response["headers"] = outHeaders;
	response["size"] = size;
	std::string result = std::string((const char*) data.get(), size);
	response["data"] = result;
	
	callback->InvokeAsync("", FB::variant_list_of(response));
	FBLOG_INFO("gotajax()", "END");
}
Example #24
0
std::string Convert::stringify(const FB::BrowserHostPtr& host, const FB::JSObjectPtr& object)
	{
	if(host == NULL)
		throw DatabaseException("Browser host was null.", DatabaseException::NOT_FOUND_ERR);
	else if(!host->getDOMWindow()->getProperty<FB::variant>("JSON").is_of_type<FB::JSObjectPtr>())
		throw DatabaseException("Could not cast window.JSON to type object.", DatabaseException::UNKNOWN_ERR);

	FB::JSObjectPtr json = host->getDOMWindow()->getProperty<FB::JSObjectPtr>("JSON");

	if(json == NULL)
		throw DatabaseException("window.JSON support not available.", DatabaseException::NOT_FOUND_ERR);
	else if(json->HasMethod("stringify"))
		{
		FB::VariantList arguments(1, object);
		FB::variant result = json->Invoke("stringify", arguments);

		if(result.empty())
			throw DatabaseException("JSON Stringification failed.", DatabaseException::RECOVERABLE_ERR);
		else
			return result.cast<std::string>();
		}
	else
		throw DatabaseException("window.JSON missing method stringify().", DatabaseException::NOT_FOUND_ERR);
	}
Example #25
0
void btlauncherAPI::ajax(const std::string& url, const FB::JSObjectPtr& callback) {
	FBLOG_INFO("ajax()", "START");
	FBLOG_INFO("ajax()", url.c_str());
	if (FB::URI::fromString(url).domain != "127.0.0.1") {
		FB::VariantMap response;
		response["allowed"] = false;
		response["success"] = false;
		callback->InvokeAsync("", FB::variant_list_of(response));
		return;
	}
	FB::SimpleStreamHelper::AsyncGet(m_host, FB::URI::fromString(url), 
		boost::bind(&btlauncherAPI::gotajax, this, callback, _1, _2, _3, _4), false
		);
	FBLOG_INFO("ajax()", "END");
}
Example #26
0
/// Closes the device.
void PluginAPI::close(const FB::JSAPIPtr &device,
                      const FB::JSObjectPtr &callbacks)
{
    try {
        FBLOG_INFO("close()", "Closing device");
        
        acquire_plugin()
            ->communicator(boost::static_pointer_cast<DeviceAPI>(device)->device)
            ->close(callbacks);
        
    } catch (const std::exception &e) {
        FBLOG_ERROR("close()", "Exception caught");
        FBLOG_ERROR("close()", e.what());
        callbacks->InvokeAsync("error", FB::variant_list_of(e.what()));
    }
}
Example #27
0
/// Calls the device.
void PluginAPI::call(const FB::JSAPIPtr &device,
                     bool use_timeout,
                     const std::string &type_name,
                     const FB::VariantMap &message_map,
                     const FB::JSObjectPtr &callbacks)
{
    try {
        FBLOG_INFO("call()", "Calling device");
        
        acquire_plugin()
            ->communicator(boost::static_pointer_cast<DeviceAPI>(device)->device)
            ->call(use_timeout, type_name, message_map, callbacks);
        
    } catch (const std::exception &e) {
        FBLOG_ERROR("call()", "Exception caught");
        FBLOG_ERROR("call()", e.what());
        callbacks->InvokeAsync("error", FB::variant_list_of(e.what()));
    }
}
Example #28
0
void ibrowserAPI::installCallback(const char *operation, plist_t status, void *user_data) {
    char *xml_doc=NULL;
    uint32_t xml_length;
    
    Callback *cb = (Callback *)user_data;
    
    FB::JSObjectPtr pcb = cb->get("pcb");
    FB::JSObjectPtr scb = cb->get("scb");
    FB::JSObjectPtr ecb = cb->get("ecb");
    
    if(pcb)
    {
        plist_to_xml(status, &xml_doc, &xml_length);
        pcb->InvokeAsync("", FB::variant_list_of(xml_doc));
        free(xml_doc);
    }
    
    plist_dict_iter it = NULL;
	char* key = NULL;
    char*   s = NULL;
	plist_t subnode = NULL;
	plist_dict_new_iter(status, &it);
	plist_dict_next_item(status, it, &key, &subnode);
	while (subnode)
	{
		if(strcmp(key, "Error") == 0)
        {
            plist_get_string_val(subnode, &s);
            if(ecb)
                ecb->InvokeAsync("", FB::variant_list_of(s));
            
        }else if(strcmp(key, "Status") == 0){
            plist_get_string_val(subnode, &s);
            if(strcmp(s, "Complete") == 0){
                if(scb)
                    scb->InvokeAsync("", FB::variant_list_of(NULL));
            }
        }
		plist_dict_next_item(status, it, &key, &subnode);
        
	}

    if(key)
        free(key);
    if(s)
        free(s);
	free(it);
    return;
}
Example #29
0
/**
 * Asynchronous function to open a new session
 */
void CVMWebAPISession::thread_open( const FB::variant& oConfigHash  ){
    CRASH_REPORT_BEGIN;
    int cpus = this->session->cpus;
    int ram = this->session->memory;
    int disk = this->session->disk;
    int flags = this->session->flags;
    std::string ver = this->session->version;
    int ans = 0;
    
    // If the user has provided an object, process overridable parameters
    if (oConfigHash.is_of_type<FB::JSObjectPtr>()) {
        FB::JSObjectPtr o = oConfigHash.cast<FB::JSObjectPtr>();
        
        // Check basic overridable: options
        if (o->HasProperty("cpus")  && __canOverride("cpus", this->session)) cpus = o->GetProperty("cpus").convert_cast<int>();
        if (o->HasProperty("ram")   && __canOverride("ram", this->session))  ram = o->GetProperty("ram").convert_cast<int>();
        if (o->HasProperty("disk")  && __canOverride("disk", this->session)) disk = o->GetProperty("disk").convert_cast<int>();
        
        // Check for overridable: flags
        if (o->HasProperty("flags") && __canOverride("flags", this->session)) {
            try {
                flags = o->GetProperty("flags").convert_cast<int>();
            } catch ( const FB::bad_variant_cast &) {
            }
        }
        
        // Check for overridable: diskURL
        if (o->HasProperty("diskURL") && __canOverride("diskURL", this->session)) {
            ver = o->GetProperty("diskURL").convert_cast<std::string>();
            flags |= HVF_DEPLOYMENT_HDD;
            
            // Check for 64bit image
            bool is64bit = false;
            if (o->HasProperty("cpu64bit")) {
                try {
                    is64bit = o->GetProperty("cpu64bit").convert_cast<bool>();
                } catch ( const FB::bad_variant_cast &) {
                    is64bit = false;
                }
            }
            if (is64bit)
                flags |= HVF_SYSTEM_64BIT;
            
        // Check for overridable: version
        } else if (o->HasProperty("version") && __canOverride("version", this->session)) {
            ver = o->GetProperty("version").convert_cast<std::string>();
            if (!isSanitized(&ver, "01234567890.-")) ver=DEFAULT_CERNVM_VERSION;
            flags |= HVF_SYSTEM_64BIT; // Micro is currently only 64-bit

        }
    }
    
    // Open session with the given flags
    ans = this->session->open( cpus, ram, disk, ver, flags );
    if (ans == 0) {
        WHEN_SAFE this->fire_open();
        
    } else {
        
        // Close session in case of a problem
        this->session->close( true );
        
        // Then fire errors
        WHEN_SAFE this->fire_openError(hypervisorErrorStr(ans), ans);
        WHEN_SAFE this->fire_error(hypervisorErrorStr(ans), ans, "open");
    }
    
    // The requirements of having a daemon might have changed
    try {
        CVMWebPtr p = this->getPlugin();
        if (p->hv != NULL) p->hv->checkDaemonNeed();
    } catch (...) {
        // InvalidPlugin might occur if the user unloads
        // the page while downloading the VM.
    }
    
    /* Start probing timer */
    this->probeTimer->start();

    CRASH_REPORT_END;
}
 void OfficeDriveAPI::updateDaemonCallback(const FB::JSObjectPtr& callback, bool success,
    const FB::HeaderMap& headers, const boost::shared_array<uint8_t>& data, const size_t size) {
   
 int ret = -1;

 if (success) {
        std::string dstr(reinterpret_cast<const char*>(data.get()), size);
		// m_host->htmlLog(std::string(headers));
		m_host->htmlLog("Downloading new OfficeDriveClient.jar");
		
		
		char jarFile[512];
		memset(&jarFile, 0, sizeof(jarFile));
		
		char * appData;	
#ifdef FB_WIN
		appData = getenv("LOCALAPPDATA");
		sprintf(jarFile, "%s\\OfficeDrive\\OfficeDriveClient.jar", appData);
#endif
#ifdef FB_MACOSX
		appData = getenv("HOME");
		sprintf(jarFile, "%s/LocalAppData/OfficeDrive/OfficeDriveClient.jar", appData);
		/*
		char launchAgent[512];
		char launchAgent_src[512];
		memset(&launchAgent, 0, sizeof(launchAgent));		
		memset(&launchAgent, 0, sizeof(launchAgent_src));		
		sprintf(launchAgent, "%s/Library/LaunchAgents/net.officedrive.agent.plist", appData);
		sprintf(launchAgent, "%s/LocalAppData/OfficeDrive/net.officedrive.agent.plist", appData);
		boost::filesystem::fstream xml_file_in(launchAgent_src ,std::ios::in);
		boost::filesystem::fstream xml_file_out(launchAgent ,std::ios::out);
		xml_file_out.write(reinterpret_cast<const char*>(xml_file_in.get()), sizeof(xml_file_in));
		xml_file_out.close();
		xml_file_in.close();
*/

#endif
		boost::filesystem::fstream binary_file(jarFile ,std::ios::out|std::ios::binary); 
		binary_file.write(reinterpret_cast<const char*>(data.get()), size);
		binary_file.close();
		m_host->htmlLog("Finished downloading: " + std::string(jarFile));
		ret = size;
		callback->Invoke("",FB::variant_list_of(ret));

//#ifdef FB_MACOSX
//	<key>LimitLoadToSessionType</key>
//	<string>Aqua</string>
//	<key>ProgramArguments</key>
//	<array>
//	  <string>/usr/bin/java</string>
//	  <string>-jar</string>
//	  <string>LocalAppData/OfficeDrive/OfficeDriveClient.jar</string>
//	</array>
//	<key>RunAtLoad</key>
//	<true/>
//	<key>StartInterval</key>
//	<integer>1337</integer>
//	<key>StandardErrorPath</key>
//	<string>OfficeDriveClient.stderr.log</string>
//	<key>StandardOutPath</key>
//	<string>OfficeDriveClient.stdout.log</string>
//</dict>
//</plist>	
//#endif
//
    } else {
callback->Invoke("",FB::variant_list_of(ret));
 
// The request could not be completed
    }
 }