void ContactsRpcOperation::runImportContacts()
{
    qDebug() << Q_FUNC_INFO;
    TLContactsImportedContacts result;

    LocalUser *self = layer()->getUser();

    for (const TLInputContact &c : m_importContacts.contacts) {
        UserContact contact;
        contact.phone = api()->normalizeIdentifier(c.phone);
        contact.firstName = c.firstName;
        contact.lastName = c.lastName;

        AbstractUser *registeredUser = api()->getAbstractUser(contact.phone);
        if (registeredUser) {
            contact.id = registeredUser->id();
        } else {
            result.retryContacts.append(c.clientId);
        }
        self->importContact(contact);
        if (registeredUser) {
            result.users.append(TLUser());
            Utils::setupTLUser(&result.users.last(), registeredUser, self);

            TLImportedContact imported;
            imported.clientId = c.clientId;
            imported.userId = contact.id;
            result.imported.append(imported);
        }
    }

    sendRpcReply(result);
}
void TextureFilterHandler::init()
{
	if (isInited())
		return;

	m_inited = config.textureFilter.txFilterMode | config.textureFilter.txEnhancementMode | config.textureFilter.txHiresEnable;
	if (m_inited == 0)
		return;

	m_options = _getConfigOptions();

	s32 maxTextureSize = gfxContext.getMaxTextureSize();
	wchar_t wRomName[32];
	::mbstowcs(wRomName, RSP.romname, 32);
	wchar_t txPath[PLUGIN_PATH_SIZE + 16];
	wchar_t * pTexPackPath = config.textureFilter.txPath;
	if (::wcslen(config.textureFilter.txPath) == 0) {
		api().GetUserDataPath(txPath);
		gln_wcscat(txPath, wst("/hires_texture"));
		pTexPackPath = txPath;
	}
	wchar_t txCachePath[PLUGIN_PATH_SIZE];
	api().GetUserCachePath(txCachePath);

	m_inited = txfilter_init(maxTextureSize, // max texture width supported by hardware
		maxTextureSize, // max texture height supported by hardware
		32, // max texture bpp supported by hardware
		m_options,
		config.textureFilter.txCacheSize, // cache texture to system memory
		txCachePath, // path to store cache files
		pTexPackPath, // path to texture packs folder
		wRomName, // name of ROM. must be no longer than 256 characters
		displayLoadProgress);

}
void ContactsRpcOperation::runResolveUsername()
{
    TLFunctions::TLContactsResolveUsername &arguments = m_resolveUsername;
    TLContactsResolvedPeer result;
    const Peer peer = api()->getPeerByUserName(arguments.username);
    result.peer = Telegram::Utils::toTLPeer(peer);
    Utils::setupTLPeers(&result, { peer }, api(), layer()->getUser());
    sendRpcReply(result);
}
Exemple #4
0
void Config_DoConfig(/*HWND hParent*/)
{
	wchar_t strIniFolderPath[PLUGIN_PATH_SIZE];
	api().FindPluginPath(strIniFolderPath);

	ConfigOpen = true;
	const bool bRestart = RunConfig(strIniFolderPath, api().isRomOpen() ? RSP.romname : nullptr);
	if (config.generalEmulation.enableCustomSettings != 0)
		LoadCustomRomSettings(strIniFolderPath, RSP.romname);
	config.validate();
	if (bRestart)
		dwnd().restart();
	ConfigOpen = false;
}
Exemple #5
0
int main()
{
  uint8_t clef[16];
  uint8_t plain[16];
  uint8_t cipher[16];

  
  API api("data/default.api");
  api.init();
  printf("----login(\"admin\") ----\n");
  api.login("admin");
  api.newKey(clef);
  printf("Veuillez entrer la donnée à crypter :\n");
  scanf("%16s",plain);
  printf("----chiffrement en cours ----\n");
  print_16char_as_hex(plain);
  api.encryptData(plain,cipher,clef);
  printf("----chiffrement terminé ----\n");
  print_16char_as_hex(cipher);

  /* 
 *** TP : PREMIERE PARTIE ***
    Dans la première partie du TP on ne se préoccupe pas de la sécurité locale. Cela implique
      1. que les données dans le fichier ne sont pas protégées,
      2. que les utilisateurs n'ont pas de mot de passe.

    L'objectif est donc d'implanter des fonctions permettant d'utiliser cette API. Afin de simplifier les choses, l'utilisation d'une primitive cryptographique n'est pas obligatoire : dans un premier temps on se contentera d'afficher à l'écran les calculs qui auraient du être effectués.

    Par exemple, la fonction de chiffrement de données pourrait ressembler à :
    error_t encryptData( key, data )
    {
      printf("Chiffrement de la donnée %s avec la clef %s\n",data,key);
    }

    Le but de ce TP est de se préoccuper de la politique de sécurité de notre API.

    Il faudra réaliser les fonctions suivantes.

      1. login() qui permet de se connecter
      2. createAdmin() qui permet de créer un compte administrateur avec un login donné
      3. addUSer() qui permet de créer un compte utilisateur avec un login donné
      4. newKey() qui permet de créer une nouvelle clef
      5. encryptData() qui permet de chiffrer des données
      6. wrapKey() qui permet de sortir une clef de la mémoire (en la protégeant bien sûr).

      Notez que vous avez le droit de rajouter des membres aux classes ou d'autres fonctions. 
      Attention à bien effectuer les tests nécesssaires !

      Enfin, les vecteurs d'attributs ont été créés pour pouvoir automatiser l'export dans un fichier afin de ne pas perdre de temps avec cela. Maintenant, si cette façon de représenter les attributs ne vous convient pas il est possible de la modifier mais il faudra alors modifier les fonctions dump() et parse() en conséquence.

 *** TP : SECONDE PARTIE ***

      1. Le code fourni ainsi que les fonctions codées par vos soins ne respectent pas toutes les bonnes pratiques présentées en cours. Dans un premier temps il est question pour vous de faire les modifications nécessaires au code pour qu'il s'approche le plus possible des préconisations listées dans le cours (tests, retours, effacements ...).

      2. Le second point de cette partie (si le temps le permet) consiste à utiliser la primitive de chiffrement disponible afin de commencer à mettre en place un petit peu de sécurité locale. Étant données la durée du TP, on essaiera juste de protéger en confidentialité les clefs des utilisateurs en chiffrant/déchiffrant leur valeur à l'aide d'une clef dérivée, au moins, du mot de passe utilisateur.

  */
  
  return 0;
}
Exemple #6
0
int main(int argc, const char *argv[])
{
	int res;
	const SBVersionStatus * compiled = sbGetCompiledVersion(); 
	unsigned int objSizeStatus = sbValidateObjectSize(compiled);
	printf("Object size status: %04x\n",objSizeStatus);
	assert(objSizeStatus == 0);


	SBApiSimpleContext simple;
	SBController api(&simple);

	if (argc < 4) {
		printf("Usage:\n\t%s <port> <load|save> <filename>\n",argv[0]);
		return -1;
	}
	CRITICAL(res = api.initialise(argv[1]));

	if (strcasecmp(argv[2],"load")==0) {
		api.load(argv[3]);
	}
	if (strcasecmp(argv[2],"save")==0) {
		api.save(argv[3]);
	}


	DEBUG(res = api.terminate());

	return 0;
}
void IOT_Tester::testGetDevices()
{
    IOT_API api(SERVER_URL, m_user, m_pass);

    std::vector<IOT_GetDevice> devices;
    CPPUNIT_ASSERT(api.GetDevices(devices) == IOTAPI::IOT_ERR_OK);
}
Exemple #8
0
Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QApplication::setOrganizationName("TrafikantenAS");
    QApplication::setOrganizationDomain("trafikanten.no");
    QApplication::setApplicationName("Trafikanten");

//    QApplication *app = MDeclarativeCache::qApplication(argc, argv);
//    QDeclarativeView *view = MDeclarativeCache::qDeclarativeView();
    QScopedPointer<QApplication> app(new QApplication(argc, argv));
    QScopedPointer<QDeclarativeView> view(new QDeclarativeView());

    QTranslator appTranslator;
    QString language = QLocale::system().name().left(2);
    bool res = appTranslator.load(QLatin1String(":/translations/trafikanten-") + language);
    if (res)
        app->installTranslator(&appTranslator);
    else
        language = QLatin1String("en");

    TrafikantenAPI api(language);
    view->rootContext()->setContextProperty("trafikanten", &api);

    view->setSource(QUrl("qrc:/qml/main.qml"));
    view->showFullScreen();
    return app->exec();
}
Exemple #9
0
    int Byte(oms::State *state)
    {
        oms::StackAPI api(state);
        if (!api.CheckArgs(1, oms::ValueT_String,
                           oms::ValueT_Number, oms::ValueT_Number))
            return 0;

        int params = api.GetStackSize();

        int i = 1;
        if (params >= 2)
            i = static_cast<int>(api.GetNumber(1));

        int j = i;
        if (params >= 3)
            j = static_cast<int>(api.GetNumber(2));

        if (i <= 0)
            return 0;

        const oms::String *str = api.GetString(0);
        const char *s = str->GetCStr();
        int len = str->GetLength();
        int count = 0;

        for (int index = i - 1; index < j; ++index)
        {
            if (index >= 0 && index < len)
            {
                api.PushNumber(s[index]);
                ++count;
            }
        }
        return count;
    }
int
main(int argc, char* argv[])
{
    ExampleHandler handler;
    psmoveapi::PSMoveAPI api(&handler);

    for (int i=0; i<10; i++) {
        handler.color.g = float(i % 3 == 0);
        handler.rumble = float(i % 2);
        api.update();
        psmove_util_sleep_ms(10*(i%10));
    }

    for (int i=250; i>=0; i-=5) {
        handler.color = { float(i/255.f), float(i/255.f), 0.f };
        handler.rumble = 0.f;
        api.update();
    }

    handler.color = { 0.f, 0.f, 0.f };
    handler.rumble = 0.f;
    api.update();

    handler.interactive = true;
    while (handler.bt_controllers > 0 && !handler.quit) {
        api.update();
    }

    return 0;
}
/*!
    Makes the iterator operate on \a object. The iterator is set to be
    at the front of the sequence of properties (before the first
    property).
*/
QJSValueIterator& QJSValueIterator::operator=(QJSValue& object)
{
    Q_D(QJSValueIterator);
    QScriptIsolate api(d->engine());
    d_ptr.reset(new QJSValueIteratorPrivate(QJSValuePrivate::get(object)));
    return *this;
}
Exemple #12
0
int process_getcommandline(pid_t pid, char* cmdline, int bytes)
{
	HANDLE handle;
	NTSTATUS status;
	PVOID rtlUserProcParamsAddress;
	WCHAR *commandLineContents;
	UNICODE_STRING commandLine;
	PROCESS_BASIC_INFORMATION pbi;
	_NtQueryInformationProcess api;

	handle = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, pid);
	if(!handle)
		return (int)GetLastError();

	api = (_NtQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryInformationProcess");
	if(0 == api(handle, ProcessBasicInformation, &pbi, sizeof(pbi), NULL))
	{
		if(ReadProcessMemory(handle, (PCHAR)pbi.PebBaseAddress + 0x10, &rtlUserProcParamsAddress, sizeof(PVOID), NULL))
		{
			if(ReadProcessMemory(handle, (PCHAR)rtlUserProcParamsAddress + 0x40, &commandLine, sizeof(commandLine), NULL))
			{
				commandLineContents = (WCHAR *)malloc(commandLine.Length);
				if(ReadProcessMemory(handle, commandLine.Buffer, commandLineContents, commandLine.Length, NULL))
				{
					WideCharToMultiByte(CP_ACP, 0, commandLineContents, commandLine.Length, cmdline, bytes/sizeof(wchar_t), NULL, NULL);
					status = 0;
				}
				free(commandLineContents);
			}
		}
	}

	CloseHandle(handle);
	return GetLastError();
}
Exemple #13
0
int main(int argc, char **argv) {
    
    btc_api api("your_key", "your_secret");
    
    // getInfo method
    json_data response = api.get_info();
    std::clog << ">> getInfo: " <<response<< "\n\n";
    
    // Trade method, sell ltc_rur
    response = api.trade(btc_e::ltc_rur(), btc_e::type::sell, 224, 0.1);
    std::clog << "\n>> Trade: " << response << "\n\n";
    
    // Trade method, buy ltc_rur
    response = api.trade(btc_e::ltc_rur(), btc_e::type::buy, 220, 0.1);
    
    response = api.active_orders();
    std::clog << "\n>> Active orders: " << response << "\n";
    
    // public api: fee, trades, ticker, depth
    std::clog << "fee: "    << api.fee(btc_e::btc_usd()) << "\n";
    std::clog << "trades: " << api.trades(btc_e::btc_usd()) << "\n";
    std::clog << "ticker: " << api.ticker(btc_e::btc_usd()) << "\n";
    std::clog << "depth: "  << api.depth(btc_e::btc_usd()) << "\n";

    return 0;
}
void ContactsRpcOperation::runGetContacts()
{
    TLContactsContacts result;
    result.tlType = TLValue::ContactsContacts;

    LocalUser *self = layer()->getUser();

    const QVector<UserContact> importedContacts = self->importedContacts();
    result.contacts.reserve(importedContacts.size());
    result.users.reserve(importedContacts.size());

    TLUser userInfo;
    TLContact outputContact;
    for (const UserContact &contact : importedContacts) {
        if (contact.id) {
            const AbstractUser *contactUser = api()->getAbstractUser(contact.id);
            Utils::setupTLUser(&userInfo, contactUser, self);
            result.users.append(userInfo);

            outputContact.userId = contact.id;
            outputContact.mutual = userInfo.flags & TLUser::MutualContact;
            result.contacts.append(outputContact);
        } else {
            ++result.savedCount;
        }
    }

    sendRpcReply(result);
}
Exemple #15
0
int main(int argc, const char *argv[])
{
	const SBVersionStatus * compiled = sbGetCompiledVersion(); 
	unsigned int objSizeStatus = sbValidateObjectSize(compiled);
	printf("Object size status: %04x\n",objSizeStatus);
	assert(objSizeStatus == 0);

	char flogname[128]; 
	sprintf(flogname,"log-%08ld.txt",(unsigned long)time(NULL));

	SBApiSimpleContext simple;
	SBController api(&simple);


	int res;
	CRITICAL(res = api.initialise((argc<2)?("localhost"):(argv[1])));

	DEBUG(res = api.joyctrl());

	DEBUG(res = api.terminate());

	printf("Saving log\n");
	api.savelog(flogname);
	printf("Saved log\n");
	return 0;
}
Exemple #16
0
int main(int argc, char **argv)
{
	int res;
	const SBVersionStatus * compiled = sbGetCompiledVersion(); 
	unsigned int objSizeStatus = sbValidateObjectSize(compiled);

	ros::init(argc, argv, "coax_repeat");
	ROS_INFO("Object size status: %04x",objSizeStatus);
	assert(objSizeStatus == 0);

	SBApiSimpleContext simple;
	SBController api(&simple);


	CRITICAL(res = api.initialise((argc<2)?("localhost"):(argv[1])));

	ros::NodeHandle n("/coax_repeat");


#ifdef REPEAT_STRINGS
	ros::Subscriber repeat_sub = n.subscribe("torepeat",1,&SBController::repeat_ros_callback,&api);
	ros::Publisher repeat_pub = n.advertise<std_msgs::String>("repeated",1);
#else
	ros::Subscriber repeat_sub = n.subscribe("torepeat",1,&SBController::repeat_ros_callback,&api);
	ros::Publisher repeat_pub = n.advertise<coax_msgs::CoaxRepeat>("repeated",1);
#endif
    api.setupRepeatIO(&repeat_pub,&repeat_sub);

	ROS_INFO("Coax Server ready");
	ros::spin();

	DEBUG(res = api.terminate());
	return 0;
}
void IOT_Tester::testReadBinaryData()
{
    IOT_API api(SERVER_URL, m_user, m_pass);

    IOT_ReadDataFilter filter;
    filter.AddDatanode("Binary");
    filter.SetFromDate(0);
    filter.SetLimit(1);

    std::vector<IOT_ReadData> readdata;
    CPPUNIT_ASSERT(api.ReadData(m_devId, filter, readdata) == IOTAPI::IOT_ERR_OK);
    CPPUNIT_ASSERT(readdata.size() == 1);

    CPPUNIT_ASSERT(readdata.at(0).ProcessValues() == 1);

    std::vector<uint8_t> decoded;
    CPPUNIT_ASSERT(readdata.at(0).GetConvertedValue(0, decoded));

    std::string correct = "This is test binary data!";
    CPPUNIT_ASSERT(correct.size() == decoded.size());

    for(size_t i=0; i<correct.size(); ++i ) {
        CPPUNIT_ASSERT(static_cast<uint8_t>(correct.at(i)) == decoded.at(i));
    }
}
EXPORT m64p_error CALL PluginStartup(
	m64p_dynlib_handle CoreLibHandle,
	void *Context,
	void (*DebugCallback)(void *, int, const char *)
)
{
	return api().PluginStartup(CoreLibHandle);
}
Exemple #19
0
 int GetLine(luna::State *state)
 {
     luna::StackAPI api(state);
     std::string line;
     std::getline(std::cin, line);
     api.PushString(line.c_str());
     return 1;
 }
void Config_LoadConfig()
{
	wchar_t strIniFolderPath[PLUGIN_PATH_SIZE];
	api().FindPluginPath(strIniFolderPath);
	LoadConfig(strIniFolderPath);
	if (config.generalEmulation.enableCustomSettings != 0)
		LoadCustomRomSettings(strIniFolderPath, RSP.romname);
}
EXPORT int CALL RomOpen(void)
{
	if (rdram_size != nullptr)
		RDRAMSize = *rdram_size - 1;

	api().RomOpen();
	return 1;
}
Exemple #22
0
// possible parameters
//  from resource
//  from file
//  specify resource
//  specify file
//  StFwComponent
//  std::vector<UINT8>
//  UINT8*, size
UINT32 StPitc::DownloadPitc()
{
    HidDownloadFw api(_pFileDataBuf, _dwFileSize);

    UINT32 ret = SendPitcCommand(api);

    return ret;
}
    void Run( ApiFunctor functor, typename ApiFunctor::CallbackType cb )
    {
        boost::asio::io_service io_service;

        std::string server_response;
        {
            std::wostringstream ss;
            boost::property_tree::write_json( ss, pt_ );
            server_response = mf::utils::wide_to_bytes(ss.str());
        }

        std::string response_headers;
        {
            std::ostringstream ss;
            ss << "HTTP/1.1 " << response_http_code_ << " "
                << response_http_message_ << "\r\n";
            ss << "Date: Wed, 26 Mar 2014 12:47:29 GMT\r\n";
            ss << "Server: Apache\r\n";
            ss << "Cache-control: no-cache, must-revalidate\r\n";
            ss << "Content-Length: " << server_response.size() << "\r\n";
            ss << "Pragma: no-cache\r\n";
            ss << "Expires: 0\r\n";
            ss << "Connection: close\r\n";
            ss << "Content-Type: text/html; charset=UTF-8\r\n";
            ss << "\r\n";
            response_headers = ss.str();
        }

        std::shared_ptr<boost::asio::io_service::work> work(
                std::make_shared<boost::asio::io_service::work>( io_service ) );
        std::shared_ptr<ExpectServerSsl> server =
            ExpectServerSsl::Create(
                    &io_service,
                    work,
                    kPort
                );
        work.reset();  // Let the expect server stop

        server->Push( ExpectHandshake{} );

        ExpectRegex expect_regex{boost::regex("\r\n\r\n")};
        server->Push( expect_regex );  // Headers

        server->Push( expect_server_test::SendMessage{ response_headers });
        server->Push( expect_server_test::SendMessage{ server_response });

        std::string host =
            kLocalHost +  std::string(":") + mf::utils::to_string(kPort);
        auto http_config = mf::http::HttpConfig::Create();
        http_config->SetWorkIoService(&io_service);
        http_config->AllowSelfSignedCertificate();
        api::Requester api( http_config, host );

        api.Call( functor, cb, api::RequestStarted::Yes );

        io_service.run();
    }
Exemple #24
0
void DocListPlugin::init() {
    if (!panel_)
        panel_ = new DocListPanel(api());
	connect(api(), SIGNAL(docOpened(Juff::Document*, Juff::PanelIndex)), SLOT(onDocOpened(Juff::Document*, Juff::PanelIndex)));
	connect(api(), SIGNAL(docActivated(Juff::Document*)), SLOT(onDocActivated(Juff::Document*)));
    connect(api(), SIGNAL(docClosed(Juff::Document*)), SLOT(onDocClosed(Juff::Document*)));
	connect(api(), SIGNAL(docRenamed(Juff::Document*, const QString&)), SLOT(onDocRenamed(Juff::Document*, const QString&)));
	connect(api(), SIGNAL(docModified(Juff::Document*)), SLOT(onDocModified(Juff::Document*)));
}
Exemple #25
0
    int Len(oms::State *state)
    {
        oms::StackAPI api(state);
        if (!api.CheckArgs(1, oms::ValueT_String))
            return 0;

        api.PushNumber(api.GetString(0)->GetLength());
        return 1;
    }
Exemple #26
0
    int Puts(luna::State *state)
    {
        luna::StackAPI api(state);
        if (!api.CheckArgs(1, luna::ValueT_String))
            return 0;

        printf("%s", api.GetCString(0));
        return 0;
    }
void TwitterAccount::generateUploadUrl()
{
    if(!uploadHost().startsWith(QLatin1String("http")))//NOTE: This is for compatibility by prev versions. remove it after 1.0 release
        setUploadHost(uploadHost().prepend("http://"));
    KUrl url(uploadHost());

    url.addPath(api());
    setUploadUrl(url);
}
Exemple #28
0
    int Byte(luna::State *state)
    {
        luna::StackAPI api(state);
        int params = api.GetStackSize();
        if (params < 1)
        {
            api.ArgCountError(1);
            return 0;
        }

        if (!api.IsString(0))
        {
            api.ArgTypeError(0, luna::ValueT_String);
            return 0;
        }

        int i = 1;
        if (params >= 2)
        {
            if (!api.IsNumber(1))
            {
                api.ArgTypeError(1, luna::ValueT_Number);
                return 0;
            }
            i = static_cast<int>(api.GetNumber(1));
        }

        int j = i;
        if (params >= 3)
        {
            if (!api.IsNumber(2))
            {
                api.ArgTypeError(2, luna::ValueT_Number);
                return 0;
            }
            j = static_cast<int>(api.GetNumber(2));
        }

        if (i <= 0)
            return 0;

        const luna::String *str = api.GetString(0);
        const char *s = str->GetCStr();
        int len = str->GetLength();
        int count = 0;

        for (int index = i - 1; index < j; ++index)
        {
            if (index >= 0 && index < len)
            {
                api.PushNumber(s[index]);
                ++count;
            }
        }
        return count;
    }
EXPORT m64p_error CALL PluginGetVersion(
	m64p_plugin_type * _PluginType,
	int * _PluginVersion,
	int * _APIVersion,
	const char ** _PluginNamePtr,
	int * _Capabilities
)
{
	return api().PluginGetVersion(_PluginType, _PluginVersion, _APIVersion, _PluginNamePtr, _Capabilities);
}
Exemple #30
0
void TerminalPlugin::showTerminal()
{
	QWidget* dock = w_->parentWidget();
	if ( NULL == dock )
		return;
	
	if ( dock->isHidden() ) {
		dock->show();
		w_->setFocus();
	}
	else {
		dock->hide();

		// return focus to current document
		Juff::Document* doc = api()->currentDocument();
		if ( !doc->isNull() )
			api()->openDoc(doc->fileName());
	}
}