示例#1
0
boolean WiFlyDevice::join(const char *ssid) {
  /*
   */
  // TODO: Handle other authentication methods
  // TODO: Handle escaping spaces/$ in SSID
  // TODO: Allow for timeout?

  // TODO: Do we want to set the passphrase/key to empty when they're
  //       not required? (Probably not necessary as I think module
  //       ignores them when they're not required.)

  sendCommand("join ", true);
  // TODO: Actually detect failure to associate
  // TODO: Handle connecting to Adhoc device
  if (sendCommand(ssid, false, "Associated!")) {
    // TODO: Extract information from complete response?
    // TODO: Change this to still work when server mode not active
    waitForResponse("Listen on ");
	
    skipRemainderOfResponse();
    return true;
  }
  return false;
}
示例#2
0
bool smtpClientClass::connectToHost()
{
    socket->connectToHostEncrypted(host, port);

    if(socket->waitForConnected(connectionTimeout) == false)
    {
        return false;
    }
    if(waitForResponse() == false)
    {
        return false;
    }
    if(responseCode != 220)
    {
        return false;
    }

    if(sendAndWait("EHLO you") == false)
    {
        return false;
    }

    return true;
}
示例#3
0
bool SmtpClient::connectToHost()
{
    switch (connectionType)
    {
    case TlsConnection: break;
    case TcpConnection:
        socket->connectToHost(host, port);
        break;
    case SslConnection:
        ((QSslSocket*) socket)->connectToHostEncrypted(host, port);
        break;

    }

    // Tries to connect to server
    if (!socket->waitForConnected(connectionTimeout))
    {
        emit smtpError(ConnectionTimeoutError);
        return false;
    }

    try
    {
        // Wait for the server's response
        waitForResponse();

        // If the response code is not 220 (Service ready)
        // means that is something wrong with the server
        if (responseCode != 220)
        {
            emit smtpError(ServerError);
            return false;
        }

        // Send a EHLO/HELO message to the server
        // The client's first command must be EHLO/HELO
        sendMessage("EHLO " + name);

        // Wait for the server's response
        waitForResponse();

        // The response code needs to be 250.
        if (responseCode != 250) {
            emit smtpError(ServerError);
            return false;
        }

        if (connectionType == TlsConnection) {
            // send a request to start TLS handshake
            sendMessage("STARTTLS");

            // Wait for the server's response
            waitForResponse();

            // The response code needs to be 220.
            if (responseCode != 220) {
                emit smtpError(ServerError);
                return false;
            };

            ((QSslSocket*) socket)->startClientEncryption();

            if (!((QSslSocket*) socket)->waitForEncrypted(connectionTimeout)) {
                qDebug() << ((QSslSocket*) socket)->errorString();
                emit smtpError(ConnectionTimeoutError);
                return false;
            }

            // Send ELHO one more time
            sendMessage("EHLO " + name);

            // Wait for the server's response
            waitForResponse();

            // The response code needs to be 250.
            if (responseCode != 250) {
                emit smtpError(ServerError);
                return false;
            }
        }
    }
    catch (ResponseTimeoutException)
    {
        return false;
    }
    catch (SendMessageTimeoutException)
    {
        return false;
    }

    // If no errors occured the function returns true.
    return true;
}
示例#4
0
ULXR_API_IMPL(MethodResponse) Requester::waitForResponse()
{
  ULXR_TRACE(ULXR_PCHAR("waitForResponse"));
  return waitForResponse(protocol, wbxml_mode);
}
示例#5
0
  Requester::call (const MethodCall& calldata, const CppString &rpc_root)
{
   ULXR_TRACE(ULXR_PCHAR("call"));
   send_call (calldata, rpc_root);
   return waitForResponse();
}
示例#6
0
文件: bacnet.c 项目: ceppa/socket
int operateBacnet(int id_device)
/*--------------------------------------------
 * invia / riceve pacchetti
 * aggiorna tabella dati
 * int id_device - identificatore device [0-NUMBACNETDEVICES-1]
 * assumo che il device sia enabled e abbia sockfd>0
 * -----------------------------------------*/
{
	int id_device_line;
	int id_bacnet_line;
	int i;
	int sock;
	int id=0;
	int out=-1;
	unsigned long object_instance,object_type,identifier,value;
	int received=0;
	int sent=0;

	for(i=0;i<NUMBACNETLINES;i++)
	{
		id_device_line=bacnetDeviceToId(bacnetTable[i].id_bacnet_device);
		if(id_device_line==id_device)
		{
			sock=bacnetDevices[id_device].sockfd;
			object_type=bacnetTable[i].object_type;
			object_instance=bacnetTable[i].object_instance;
			identifier=(object_type<<22)|object_instance;
			if((sock!=-1)&&(sendBacnetRequest(sock,
					identifier,bacnetDevices[id_device].address,id)))
			{
				sent++;
				if(waitForResponse(sock,BACNET_TIMEOUT))
				{
					if(receiveBacnetResponse(sock,&identifier,&value)!=-1)
					{
						received++;
						id_bacnet_line=bacnetIdentifierToId(
							bacnetDevices[id_device].id,
							identifier);
// gestione sforamenti e allarmi 
						if(bacnetTable[id_bacnet_line].object_type==3)
						{
							if((bacnetTable[id_bacnet_line].value==1)
								&&(value==0)&&(bacnetTable[id_bacnet_line].hi_low_msg))
								handleMessage(
									BACNET,
									bacnetTable[id_bacnet_line].id,
									bacnetTable[id_bacnet_line].id_bacnet_device,
									0,
									bacnetTable[id_bacnet_line].hi_low_msg,
									0,
									ALARM_NO_STORE);
							if((bacnetTable[id_bacnet_line].value==0)
								&&(value==1)&&(bacnetTable[id_bacnet_line].low_hi_msg))
								handleMessage(
									BACNET,
									bacnetTable[id_bacnet_line].id,
									bacnetTable[id_bacnet_line].id_bacnet_device,
									0,
									bacnetTable[id_bacnet_line].low_hi_msg,
									0,
									ALARM_NO_STORE);
							if(bacnetTable[id_bacnet_line].is_alarm)
							{
								if((bacnetTable[id_bacnet_line].value==0)&&(value==1))
									handleMessage(
										BACNET,
										bacnetTable[id_bacnet_line].id,
										bacnetTable[id_bacnet_line].id_bacnet_device,
										0,
										bacnetTable[id_bacnet_line].alarm_msg,
										0,
										ALARM_AS_ALARM);
								if((bacnetTable[id_bacnet_line].value==1)&&(value==0))
									handleMessage(
										BACNET,
										bacnetTable[id_bacnet_line].id,
										bacnetTable[id_bacnet_line].id_bacnet_device,
										0,
										"value in range",
										0,
										ALARM_BACK_IN_RANGE);
							}
						}
// fine gestione sforamenti e allarmi 
						bacnetTable[id_bacnet_line].value_valid=TRUE;
						bacnetTable[id_bacnet_line].value=value;

//gestione max e min del giorno

					}
					else
					{
						id_bacnet_line=bacnetIdentifierToId(
							bacnetDevices[id_device].id,
							identifier);

						bacnetTable[id_bacnet_line].value_valid=FALSE;
						bacnetTable[id_bacnet_line].value=0xffffffff;
					}
				}
			}
		}
	}
	if(received==0)
	{

		bacnetDevices[id_device].status='2';
		bacnetDevices[id_device].failures++;

		if(bacnetDevices[id_device].failures>BACNET_MAXFAILURES)
		{
			if(bacnetDevices[id_device].ok==TRUE)
				handleMessage(BACNET,0,
					bacnetDevices[id_device].id,0,
					"DEVICE DISCONNECTED",0,ALARM_AS_ALARM);
			bacnetDevices[id_device].ok=FALSE;
			bacnetDevices[id_device].failures=0;
			bacnetDevices[id_device].status='3';
			bacnetDeviceDisconnected(id_device);
			my_printf("BACNET %s error operating, sleeping 5 seconds\n",
				bacnetDevices[id_device].description);
			sleep(5);
		}
		else
			handleMessage(BACNET,0,
				bacnetDevices[id_device].id,0,
					"NO DATA RECEIVED",0,ALARM_AS_ALARM);
	}
	else
	{
		bacnetDevices[id_device].ok=TRUE;
		bacnetDevices[id_device].failures=0;
		//TODO: if received<sent increase timeout
/*		if(received<sent)
			printf("bacnet: sent %d received %d\n",sent,received);*/
		out=0;
		if(bacnetDevices[id_device].status!='0')
		{
			bacnetDevices[id_device].status='0';
			my_printf("address %s, port %d, bacnet connected\n",
				bacnetDevices[id_device].address, bacnetDevices[id_device].port);

			handleMessage(BACNET,0,
				bacnetDevices[id_device].id,0,"OPERATING OK",0,ALARM_BACK_IN_RANGE);
		}
	}
	return out;
}
/*!
    Client requests proxy object. The proxy is owned by calling
    code and this object must clean itself up upon destruction of
    proxy.
*/
QObject* ObjectEndPoint::constructProxy(const QRemoteServiceRegister::Entry& entry)
{
    // Client side
    Q_ASSERT(d->endPointType == ObjectEndPoint::Client);

    // Request a serialized meta object
    QServicePackage p;
    p.d = new QServicePackagePrivate();
    p.d->messageId = QUuid::createUuid();
    p.d->entry = entry;

    Response* response = new Response();
    openRequests()->insert(p.d->messageId, response);

    dispatch->writePackage(p);
    waitForResponse(p.d->messageId);

    // Get the proxy based on the meta object
    if (response->isFinished) {
        if (response->result == 0)
            qWarning() << "Request for remote service failed";
        else
            service = reinterpret_cast<QServiceProxy* >(response->result);
    } else {
        qDebug() << "response passed but not finished";
    }

    openRequests()->take(p.d->messageId);
    delete response;

    if (!service)
        return 0;

    // Connect all DBus interface signals to the proxy slots
    const QMetaObject *mo = service->metaObject();
    while (mo && strcmp(mo->className(), "QObject")) {
        for (int i = mo->methodOffset(); i < mo->methodCount(); i++) {
            const QMetaMethod mm = mo->method(i);
            if (mm.methodType() == QMetaMethod::Signal) {
                QByteArray sig(mm.methodSignature());

                bool customType = false;

                QList<QByteArray> params = mm.parameterTypes();
                for (int arg = 0; arg < params.size(); arg++) {
                    const QByteArray& type = params[arg];
                    int variantType = QMetaType::type(type);
                    if (variantType >= QMetaType::User || variantType == QMetaType::QVariant) {
                        sig.replace(QByteArray(type), QByteArray("QDBusVariant"));
                        customType = true;
                    }
                }

                int serviceIndex = iface->metaObject()->indexOfSignal(sig);
                QByteArray signal = QByteArray("2").append(sig);

                if (serviceIndex > 0) {
                    if (customType) {
                        QObject::connect(iface, signal.constData(), signalsObject, signal.constData());

                        ServiceSignalIntercepter *intercept =
                            new ServiceSignalIntercepter((QObject*)signalsObject, signal, this);
                        intercept->setMetaIndex(localToRemote[i]);
                    } else {
                        QObject::connect(iface, signal.constData(), service, signal.constData());
                    }
                }
            }
        }
        mo = mo->superClass();
    }

    return service;
}
示例#8
0
文件: sdk_test.cpp 项目: rezetta/sdk
/**
 * @brief TEST_F SdkTestShares
 *
 * Initialize a test scenario by:
 *
 * - Creating/uploading some folders/files to share
 * - Creating a new contact to share to
 *
 * Performs different operations related to sharing:
 *
 * - Share a folder with an existing contact
 * - Check the correctness of the outgoing share
 * - Check the reception and correctness of the incoming share
 * - Modify the access level
 * - Revoke the access to the share
 * - Share a folder with a non registered email
 * - Check the correctness of the pending outgoing share
 * - Create a public link
 * - Import a public link
 * - Get a node from public link
 * - Remove a public link
 */
TEST_F(SdkTest, SdkTestShares)
{
    MegaShareList *sl;
    MegaShare *s;
    MegaNodeList *nl;
    MegaNode *n;
    MegaNode *n1;

    getMegaApiAux();    // login + fetchnodes


    // Initialize a test scenario : create some folders/files to share

    // Create some nodes to share
    //  |--Shared-folder
    //    |--subfolder
    //    |--file.txt

    MegaNode *rootnode = megaApi->getRootNode();
    char foldername1[64] = "Shared-folder";
    MegaHandle hfolder1;

    responseReceived = false;
    megaApi->createFolder(foldername1, rootnode);
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot create a folder (error: " << lastError << ")";
    hfolder1 = h;     // 'h' is set in 'onRequestFinish()'
    n1 = megaApi->getNodeByHandle(hfolder1);

    char foldername2[64] = "subfolder";
    MegaHandle hfolder2;

    responseReceived = false;
    megaApi->createFolder(foldername2, megaApi->getNodeByHandle(hfolder1));
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot create a folder (error: " << lastError << ")";
    hfolder2 = h;

    MegaHandle hfile1;
    createFile(PUBLICFILE.data(), false);   // not a large file since don't need to test transfers here

    uploadFinished = false;
    megaApi->startUpload(PUBLICFILE.data(), megaApi->getNodeByHandle(hfolder1));
    waitForResponse(&uploadFinished);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot upload file (error: " << lastError << ")";
    hfile1 = h;


    // Initialize a test scenario: create a new contact to share to

    string message = "Hi contact. Let's share some stuff";

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( inviteContact(emailaux, message, MegaContactRequest::INVITE_ACTION_ADD) );

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)


    MegaContactRequestList *crlaux = megaApiAux->getIncomingContactRequests();
    ASSERT_EQ(1, crlaux->size()) << "Too many incoming contact requests in auxiliar account";
    MegaContactRequest *craux = crlaux->get(0);

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( replyContact(craux, MegaContactRequest::REPLY_ACTION_ACCEPT) );

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)

    delete crlaux;


    // --- Create a new outgoing share ---

    nodeUpdated = false;
    nodeUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( shareFolder(n1, emailaux.data(), MegaShare::ACCESS_READ) );

    waitForResponse(&nodeUpdated);
    waitForResponse(&nodeUpdatedAux);


    // --- Check the outgoing share ---

    sl = megaApi->getOutShares();
    ASSERT_EQ(1, sl->size()) << "Outgoing share failed";
    s = sl->get(0);

    ASSERT_EQ(MegaShare::ACCESS_READ, s->getAccess()) << "Wrong access level of outgoing share";
    ASSERT_EQ(hfolder1, s->getNodeHandle()) << "Wrong node handle of outgoing share";
    ASSERT_STREQ(emailaux.data(), s->getUser()) << "Wrong email address of outgoing share";
    ASSERT_TRUE(megaApi->isShared(n1)) << "Wrong sharing information at outgoing share";
    ASSERT_TRUE(megaApi->isOutShare(n1)) << "Wrong sharing information at outgoing share";

    delete sl;


    // --- Check the incoming share ---

    nl = megaApiAux->getInShares(megaApiAux->getContact(email.data()));
    ASSERT_EQ(1, nl->size()) << "Incoming share not received in auxiliar account";
    n = nl->get(0);

    ASSERT_EQ(hfolder1, n->getHandle()) << "Wrong node handle of incoming share";
    ASSERT_STREQ(foldername1, n->getName()) << "Wrong folder name of incoming share";
    ASSERT_EQ(MegaError::API_OK, megaApiAux->checkAccess(n, MegaShare::ACCESS_READ).getErrorCode()) << "Wrong access level of incoming share";
    ASSERT_TRUE(megaApiAux->isInShare(n)) << "Wrong sharing information at incoming share";
    ASSERT_TRUE(megaApiAux->isShared(n)) << "Wrong sharing information at incoming share";

    delete nl;


    // --- Modify the access level of an outgoing share ---

    nodeUpdated = false;
    nodeUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( shareFolder(megaApi->getNodeByHandle(hfolder1), emailaux.data(), MegaShare::ACCESS_READWRITE) );

    waitForResponse(&nodeUpdated);
    waitForResponse(&nodeUpdatedAux);

    nl = megaApiAux->getInShares(megaApiAux->getContact(email.data()));
    ASSERT_EQ(1, nl->size()) << "Incoming share not received in auxiliar account";
    n = nl->get(0);

    ASSERT_EQ(MegaError::API_OK, megaApiAux->checkAccess(n, MegaShare::ACCESS_READWRITE).getErrorCode()) << "Wrong access level of incoming share";

    delete nl;


    // --- Revoke access to an outgoing share ---

    nodeUpdated = false;
    nodeUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( shareFolder(n1, emailaux.data(), MegaShare::ACCESS_UNKNOWN) );

    waitForResponse(&nodeUpdated);
    waitForResponse(&nodeUpdatedAux);

    sl = megaApi->getOutShares();
    ASSERT_EQ(0, sl->size()) << "Outgoing share revocation failed";
    delete sl;

    nl = megaApiAux->getInShares(megaApiAux->getContact(email.data()));
    ASSERT_EQ(0, nl->size()) << "Incoming share revocation failed";
    delete nl;


    // --- Get pending outgoing shares ---

    char emailfake[64];
    srand (time(NULL));
    sprintf(emailfake, "*****@*****.**", rand()%1000000);
    // carefull, antispam rejects too many tries without response for the same address

    n = megaApi->getNodeByHandle(hfolder2);

    nodeUpdated = false;
    ASSERT_NO_FATAL_FAILURE( shareFolder(n, emailfake, MegaShare::ACCESS_FULL) );
    waitForResponse(&nodeUpdated);

    sl = megaApi->getPendingOutShares(n);
    delete n;
    ASSERT_EQ(1, sl->size()) << "Pending outgoing share failed";
    s = sl->get(0);
    n = megaApi->getNodeByHandle(s->getNodeHandle());

//    ASSERT_STREQ(emailfake, s->getUser()) << "Wrong email address of outgoing share"; User is not created yet
    ASSERT_FALSE(megaApi->isShared(n)) << "Node is already shared, must be pending";
    ASSERT_FALSE(megaApi->isOutShare(n)) << "Node is already shared, must be pending";

    delete sl;
    delete n;


    // --- Create a public link ---

    MegaNode *nfile1 = megaApi->getNodeByHandle(hfile1);

    ASSERT_NO_FATAL_FAILURE( createPublicLink(nfile1) );
    // The created link is stored in this->link at onRequestFinish()


    // --- Import a public link ---

    ASSERT_NO_FATAL_FAILURE( importPublicLink(link, rootnode) );

    MegaNode *nimported = megaApi->getNodeByHandle(h);

    ASSERT_STREQ(nfile1->getName(), nimported->getName()) << "Imported file with wrong name";
    ASSERT_EQ(rootnode->getHandle(), nimported->getParentHandle()) << "Imported file in wrong path";


    // --- Get node from public link ---

    ASSERT_NO_FATAL_FAILURE( getPublicNode(link) );

    ASSERT_TRUE(publicNode->isPublic()) << "Cannot get a node from public link";


    // --- Remove a public link ---

    ASSERT_NO_FATAL_FAILURE( removePublicLink(nfile1) );

    delete nfile1;
    nfile1 = megaApi->getNodeByHandle(h);
    ASSERT_FALSE(nfile1->isPublic()) << "Public link removal failed (still public)";

    delete nimported;
}
示例#9
0
int FontInstInterface::uninstall(const QString &name, bool fromSystem)
{
    KFI_DBUG;
    itsInterface->uninstall(name, fromSystem, getpid(), true);
    return waitForResponse();
}
示例#10
0
int FontInstInterface::install(const QString &file, bool toSystem)
{
    KFI_DBUG;
    itsInterface->install(file, true, toSystem, getpid(), true);
    return waitForResponse();
}
示例#11
0
void TerminalApiClient::data_tick()
{
    // values in milliseconds
    const int MIN_WAIT_TIME           = 20; // sleep time must be smaller or equal than the smallest period
    const int IO_POLL_PERIOD          = 20;
    const int API_EVENT_POLL_PERIOD   = 1000;

    int last_io_poll  = 0;
    int last_event_api_poll = 0;

    int last_char = 0;
    std::string inbuf;
    bool enter_was_pressed = false;

    StateToken runstate_state_token;
    std::string runstate;

    std::vector<std::string> accounts;

    StateToken password_state_token;
    bool ask_for_password = false;
    std::string key_name;

    TerminalInput term;

    while(!shouldStop())
    {
        // assuming sleep_time >> work_time
        // so we don't have to check the absolute time, just sleep every cycle
        usleep(MIN_WAIT_TIME * 1000);
        last_io_poll          += MIN_WAIT_TIME;
        last_event_api_poll   += MIN_WAIT_TIME;

        if(last_io_poll >= IO_POLL_PERIOD)
        {
            last_io_poll = 0;
            last_char = 0;
            if(term.kbhit())
            {
                enter_was_pressed = false;
                last_char = term.getch();
                if(last_char > 127)
                    std::cout << "Warning: non ASCII characters probably won't work." << std::endl;
                if(last_char >= ' ')// space is the first printable ascii character
                    inbuf += (char) last_char;
                if(last_char == '\r' || last_char == '\n')
                    enter_was_pressed = true;
                else
                    enter_was_pressed = false;
                // send echo
                if(ask_for_password)
                    std::cout << "*";
                else
                    std::cout << (char) last_char;

                //std::cout << "you pressed key " << (char) last_char  << " as integer: " << last_char << std::endl;
            }
        }

        if(last_event_api_poll >= API_EVENT_POLL_PERIOD)
        {
            last_event_api_poll = 0;
            if(!runstate_state_token.isNull() && !isTokenValid(runstate_state_token))
                runstate_state_token = StateToken(); // must get new state with new token

            if(!password_state_token.isNull() && !isTokenValid(password_state_token))
                password_state_token = StateToken();
        }

        bool edge = false;
        if(runstate_state_token.isNull())
        {
            edge = true;
            JsonStream reqs;
            JsonStream resps;
            Request req(reqs);
            std::stringstream ss;
            Response resp(resps, ss);

            req.mPath.push("runstate");
            req.mPath.push("control");
            reqs.switchToDeserialisation();

            ApiServer::RequestId id = mApiServer->handleRequest(req, resp);
            waitForResponse(id);

            resps.switchToDeserialisation();
            resps << makeKeyValueReference("runstate", runstate);
            runstate_state_token = resp.mStateToken;
        }
        if(password_state_token.isNull())
        {
            edge = true;
            JsonStream reqs;
            JsonStream resps;
            Request req(reqs);
            std::stringstream ss;
            Response resp(resps, ss);

            req.mPath.push("password");
            req.mPath.push("control");
            reqs.switchToDeserialisation();

            ApiServer::RequestId id = mApiServer->handleRequest(req, resp);
            waitForResponse(id);

            resps.switchToDeserialisation();
            resps << makeKeyValueReference("want_password", ask_for_password);
            resps << makeKeyValueReference("key_name", key_name);
            password_state_token = resp.mStateToken;
        }

        if(!ask_for_password && edge && runstate == "waiting_account_select")
        {
            JsonStream reqs;
            JsonStream resps;
            Request req(reqs);
            std::stringstream ss;
            Response resp(resps, ss);

            req.mPath.push("locations");
            req.mPath.push("control");
            reqs.switchToDeserialisation();

            ApiServer::RequestId id = mApiServer->handleRequest(req, resp);
            waitForResponse(id);

            resps.switchToDeserialisation();
            std::cout << "Type a number to select an account" << std::endl;
            if(!resps.hasMore())
                std::cout << "Error: No Accounts. Use the Qt-GUI or the webinterface to create an account." << std::endl;
            int i = 0;
            accounts.clear();
            while(resps.hasMore())
            {
                std::string id;
                std::string name;
                std::string location;
                resps.getStreamToMember()
                        << makeKeyValueReference("id", id)
                        << makeKeyValueReference("name", name)
                        << makeKeyValueReference("location", location);
                std::cout << "[" << i << "] " << name << "(" << location << ")" << std::endl;
                accounts.push_back(id);
                i++;
            }
        }

        if(!ask_for_password && runstate == "waiting_account_select"
                && last_char >= '0' && last_char <= '9'
                && (last_char-'0') < accounts.size())
        {
            std::string acc = accounts[last_char-'0'];
            JsonStream reqs;
            JsonStream resps;
            Request req(reqs);
            std::stringstream ss;
            Response resp(resps, ss);

            req.mPath.push("login");
            req.mPath.push("control");
            reqs << makeKeyValueReference("id", acc);
            reqs.switchToDeserialisation();

            ApiServer::RequestId id = mApiServer->handleRequest(req, resp);
            waitForResponse(id);

            inbuf.clear();
        }

        if(edge && ask_for_password)
        {
            std::cout << "Enter the password for key " << key_name << std::endl;
        }

        if(ask_for_password && enter_was_pressed && !inbuf.empty())
        {
            std::cout << "TerminalApiClient: got a password" << std::endl;
            JsonStream reqs;
            JsonStream resps;
            Request req(reqs);
            std::stringstream ss;
            Response resp(resps, ss);

            req.mPath.push("password");
            req.mPath.push("control");
            reqs << makeKeyValueReference("password", inbuf);
            reqs.switchToDeserialisation();

            ApiServer::RequestId id = mApiServer->handleRequest(req, resp);
            waitForResponse(id);

            inbuf.clear();
        }
    }
}
示例#12
0
/**
 * @private
 *
 * Waits for a response up to timeout, and stores the response in the
 * inputCommand array.
 *
 * @return True if response is received before the timeout, false otherwise.
 */
bool CameraC329::waitForResponse(uint32_t timeout)
{
  return waitForResponse(timeout, inputCommand, CMD_SIZE);
}
示例#13
0
文件: sdk_test.cpp 项目: rezetta/sdk
/**
 * @brief TEST_F SdkTestContacts
 *
 * Creates an auxiliar 'MegaApi' object to interact with the main MEGA account.
 *
 * - Invite a contact
 * = Ignore the invitation
 * - Delete the invitation
 *
 * - Invite a contact
 * = Deny the invitation
 *
 * - Invite a contact
 * = Accept the invitation
 *
 * - Remove contact
 *
 * TODO:
 * - Invite a contact not registered in MEGA yet (requires validation of account)
 * - Remind an existing invitation (requires 2 weeks wait)
 */
TEST_F(SdkTest, SdkTestContacts)
{
    ASSERT_NO_FATAL_FAILURE( getMegaApiAux() );    // login + fetchnodes


    // --- Check my email and the email of the contact ---

    EXPECT_STREQ(email.data(), megaApi->getMyEmail());
    EXPECT_STREQ(emailaux.data(), megaApiAux->getMyEmail());


    // --- Send a new contact request ---

    string message = "Hi contact. This is a testing message";

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( inviteContact(emailaux, message, MegaContactRequest::INVITE_ACTION_ADD) );

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)


    // --- Check the sent contact request ---

    ASSERT_NO_FATAL_FAILURE( getContactRequest(true) );

    ASSERT_STREQ(message.data(), cr->getSourceMessage()) << "Message sent is corrupted";
    ASSERT_STREQ(email.data(), cr->getSourceEmail()) << "Wrong source email";
    ASSERT_STREQ(emailaux.data(), cr->getTargetEmail()) << "Wrong target email";
    ASSERT_EQ(MegaContactRequest::STATUS_UNRESOLVED, cr->getStatus()) << "Wrong contact request status";
    ASSERT_TRUE(cr->isOutgoing()) << "Wrong direction of the contact request";

    delete cr;
    cr = NULL;


    // --- Check received contact request ---

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false) );

    ASSERT_STREQ(message.data(), craux->getSourceMessage()) << "Message received is corrupted";
    ASSERT_STREQ(email.data(), craux->getSourceEmail()) << "Wrong source email";
    ASSERT_STREQ(NULL, craux->getTargetEmail()) << "Wrong target email";    // NULL according to MegaApi documentation
    ASSERT_EQ(MegaContactRequest::STATUS_UNRESOLVED, craux->getStatus()) << "Wrong contact request status";
    ASSERT_FALSE(craux->isOutgoing()) << "Wrong direction of the contact request";

    delete craux;
    craux = NULL;


    // --- Ignore received contact request ---

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false) );

    contactRequestUpdatedAux = false;
    ASSERT_NO_FATAL_FAILURE( replyContact(craux, MegaContactRequest::REPLY_ACTION_IGNORE) );
    waitForResponse(&contactRequestUpdatedAux); // only at auxiliar account. Main account is not notified

    delete craux;
    craux = NULL;

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false, 0) );
    delete craux;
    craux = NULL;


    // --- Cancel the invitation ---

    message = "I don't wanna be your contact anymore";

    contactRequestUpdated = false;
    ASSERT_NO_FATAL_FAILURE( inviteContact(emailaux, message, MegaContactRequest::INVITE_ACTION_DELETE) );
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false, 0) );
    delete craux;
    craux = NULL;

    // The target contact doesn't receive notification, since the invitation was ignored previously


    // --- Remind a contact invitation (cannot until 2 weeks after invitation/last reminder) ---

//    contactRequestReceived = false;
//    megaApi->inviteContact(emailaux.data(), message.data(), MegaContactRequest::INVITE_ACTION_REMIND);
//    waitForResponse(&contactRequestReceived, 30); // at the target side (auxiliar account)

//    ASSERT_TRUE(contactRequestReceived) << "Contact invitation reminder not received after " << timeout  << " seconds";


    // --- Invite a new contact (again) ---

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( inviteContact(emailaux, message, MegaContactRequest::INVITE_ACTION_ADD) );

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)


    // --- Deny a contact invitation ---

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false) );

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    replyContact(craux, MegaContactRequest::REPLY_ACTION_DENY);

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)

    delete craux;
    craux = NULL;

    ASSERT_NO_FATAL_FAILURE( getContactRequest(true, 0) );
    delete cr;
    cr = NULL;

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false, 0) );
    delete craux;
    craux = NULL;


    // --- Invite a new contact (again) ---

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( inviteContact(emailaux, message, MegaContactRequest::INVITE_ACTION_ADD) );

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)


    // --- Accept a contact invitation ---

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false) );

    contactRequestUpdated = false;
    contactRequestUpdatedAux = false;

    ASSERT_NO_FATAL_FAILURE( replyContact(craux, MegaContactRequest::REPLY_ACTION_ACCEPT) );

    waitForResponse(&contactRequestUpdatedAux); // at the target side (auxiliar account)
    waitForResponse(&contactRequestUpdated);    // at the source side (main account)

    delete craux;
    craux = NULL;

    ASSERT_NO_FATAL_FAILURE( getContactRequest(true, 0) );
    delete cr;
    cr = NULL;

    ASSERT_NO_FATAL_FAILURE( getContactRequest(false, 0) );
    delete craux;
    craux = NULL;


    // --- Delete an existing contact ---

    contactRemoved = false;
    ASSERT_NO_FATAL_FAILURE( removeContact(emailaux) );
    waitForResponse(&contactRemoved);

    MegaUser *u = megaApi->getContact(emailaux.data());
    ASSERT_EQ(MegaUser::VISIBILITY_HIDDEN, u->getVisibility()) << "New contact still visible";
    delete u;
}
示例#14
0
文件: sdk_test.cpp 项目: rezetta/sdk
/**
 * @brief TEST_F SdkTestTransfers
 *
 * It performs different operations related to transfers in both directions: up and down.
 *
 * - Starts an upload transfer and cancel it
 * - Starts an upload transfer, pause it, resume it and complete it
 * - Get node by fingerprint
 * - Get size of a node
 * - Download a file
 */
TEST_F(SdkTest, SdkTestTransfers)
{
    MegaNode *rootnode = megaApi->getRootNode();
    string filename1 = UPFILE;
    createFile(filename1);


    // --- Cancel a transfer ---

    transfersCancelled = false;
    megaApi->startUpload(filename1.data(), rootnode);
    megaApi->cancelTransfers(MegaTransfer::TYPE_UPLOAD);
    waitForResponse(&transfersCancelled);

    EXPECT_EQ(MegaError::API_OK, lastError) << "Transfer cancellation failed (error: " << lastError << ")";


    // --- Upload a file (part 1) ---

    uploadFinished = false;
    megaApi->startUpload(filename1.data(), rootnode);
    // do not wait yet for completion


    // --- Pause a transfer ---

    transfersPaused = false;
    megaApi->pauseTransfers(true, MegaTransfer::TYPE_UPLOAD);
    waitForResponse(&transfersPaused);

    EXPECT_EQ(MegaError::API_OK, lastError) << "Cannot pause transfer (error: " << lastError << ")";
    EXPECT_TRUE(megaApi->areTransfersPaused(MegaTransfer::TYPE_UPLOAD)) << "Upload transfer not paused";


    // --- Resume a transfer ---

    transfersPaused = false;
    megaApi->pauseTransfers(false, MegaTransfer::TYPE_UPLOAD);
    waitForResponse(&transfersPaused);

    EXPECT_EQ(MegaError::API_OK, lastError) << "Cannot resume transfer (error: " << lastError << ")";
    EXPECT_FALSE(megaApi->areTransfersPaused(MegaTransfer::TYPE_UPLOAD)) << "Upload transfer not resumed";


    // --- Upload a file (part 2) ---

    waitForResponse(&uploadFinished);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot upload file (error: " << lastError << ")";

    MegaNode *n1 = megaApi->getNodeByHandle(h);
    bool null_pointer = (n1 == NULL);

    ASSERT_FALSE(null_pointer) << "Cannot upload file (error: " << lastError << ")";
    ASSERT_STREQ(filename1.data(), n1->getName()) << "Uploaded file with wrong name (error: " << lastError << ")";


    // --- Get node by fingerprint (needs to be a file, not a folder) ---

    char *fingerprint = megaApi->getFingerprint(n1);
    MegaNode *n2 = megaApi->getNodeByFingerprint(fingerprint);

    null_pointer = (n2 == NULL);
    EXPECT_FALSE(null_pointer) << "Node by fingerprint not found";
//    ASSERT_EQ(n2->getHandle(), n4->getHandle());  This test may fail due to multiple nodes with the same name

    delete fingerprint;


    // --- Get the size of a file ---

    int filesize = getFilesize(filename1);
    int nodesize = megaApi->getSize(n2);
    EXPECT_EQ(filesize, nodesize) << "Wrong size of uploaded file";


    // --- Download a file ---

    string filename2 = "./" + DOWNFILE;

    downloadFinished = false;
    megaApi->startDownload(n2, filename2.c_str());
    waitForResponse(&downloadFinished);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot download the file (error: " << lastError << ")";

    MegaNode *n3 = megaApi->getNodeByHandle(h);
    null_pointer = (n3 == NULL);

    ASSERT_FALSE(null_pointer) << "Cannot download node";
    ASSERT_EQ(n2->getHandle(), n3->getHandle()) << "Cannot download node (error: " << lastError << ")";

    delete rootnode;
    delete n1;
    delete n2;
    delete n3;
}
示例#15
0
文件: sdk_test.cpp 项目: rezetta/sdk
/**
 * @brief TEST_F SdkTestNodeOperations
 *
 * It performs different operations with nodes, assuming the Cloud folder is empty at the beginning.
 *
 * - Create a new folder
 * - Rename a node
 * - Copy a node
 * - Get child nodes of given node
 * - Get child node by name
 * - Get node by path
 * - Get node by name
 * - Move a node
 * - Get parent node
 * - Move a node to Rubbish bin
 * - Remove a node
 */
TEST_F(SdkTest, SdkTestNodeOperations)
{
    // --- Create a new folder ---

    MegaNode *rootnode = megaApi->getRootNode();
    char name1[64] = "New folder";

    responseReceived = false;
    megaApi->createFolder(name1, rootnode);
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot create a folder (error: " << lastError << ")";


    // --- Rename a node ---

    MegaNode *n1 = megaApi->getNodeByHandle(h);
    strcpy(name1, "Folder renamed");

    responseReceived = false;
    megaApi->renameNode(n1, name1);
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot rename a node (error: " << lastError << ")";


    // --- Copy a node ---

    MegaNode *n2;
    char name2[64] = "Folder copy";

    responseReceived = false;
    megaApi->copyNode(n1, rootnode, name2);
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot create a copy of a node (error: " << lastError << ")";
    n2 = megaApi->getNodeByHandle(h);


    // --- Get child nodes ---

    MegaNodeList *children;
    children = megaApi->getChildren(rootnode);

    EXPECT_EQ(megaApi->getNumChildren(rootnode), children->size()) << "Wrong number of child nodes";
    ASSERT_LE(2, children->size()) << "Wrong number of children nodes found";
    EXPECT_STREQ(name2, children->get(0)->getName()) << "Wrong name of child node"; // "Folder copy"
    EXPECT_STREQ(name1, children->get(1)->getName()) << "Wrong name of child node"; // "Folder rename"

    delete children;


    // --- Get child node by name ---

    MegaNode *n3;
    n3 = megaApi->getChildNode(rootnode, name2);

    bool null_pointer = (n3 == NULL);
    EXPECT_FALSE(null_pointer) << "Child node by name not found";
//    ASSERT_EQ(n2->getHandle(), n3->getHandle());  This test may fail due to multiple nodes with the same name


    // --- Get node by path ---

    char path[128] = "/Folder copy";
    MegaNode *n4;
    n4 = megaApi->getNodeByPath(path);

    null_pointer = (n4 == NULL);
    EXPECT_FALSE(null_pointer) << "Node by path not found";


    // --- Search for a node ---
    MegaNodeList *nlist;
    nlist = megaApi->search(rootnode, "copy");

    ASSERT_EQ(1, nlist->size());
    EXPECT_EQ(n4->getHandle(), nlist->get(0)->getHandle()) << "Search node by pattern failed";

    delete nlist;


    // --- Move a node ---

    responseReceived = false;
    megaApi->moveNode(n1, n2);
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot move node (error: " << lastError << ")";


    // --- Get parent node ---

    MegaNode *n5;
    n5 = megaApi->getParentNode(n1);

    ASSERT_EQ(n2->getHandle(), n5->getHandle()) << "Wrong parent node";


    // --- Send to Rubbish bin ---

    responseReceived = false;
    megaApi->moveNode(n2, megaApi->getRubbishNode());
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot move node to Rubbish bin (error: " << lastError << ")";


    // --- Remove a node ---

    responseReceived = false;
    megaApi->remove(n2);
    waitForResponse(&responseReceived);

    ASSERT_EQ(MegaError::API_OK, lastError) << "Cannot remove a node (error: " << lastError << ")";

    delete rootnode;
    delete n1;
    delete n2;
    delete n3;
    delete n4;
    delete n5;
}
示例#16
0
bool SmtpClient::login(const QString &user, const QString &password, AuthMethod method)
{
    try {
        if (method == AuthPlain)
        {
            // Sending command: AUTH PLAIN base64('\0' + username + '\0' + password)
            sendMessage("AUTH PLAIN " + QByteArray().append((char) 0).append(user).append((char) 0).append(password).toBase64());

            // Wait for the server's response
            waitForResponse();

            // If the response is not 235 then the authentication was faild
            if (responseCode != 235)
            {
                emit smtpError(AuthenticationFailedError);
                return false;
            }
        }
        else if (method == AuthLogin)
        {
            // Sending command: AUTH LOGIN
            sendMessage("AUTH LOGIN");

            // Wait for 334 response code
            waitForResponse();
            if (responseCode != 334) { emit smtpError(AuthenticationFailedError); return false; }

            // Send the username in base64
            sendMessage(QByteArray().append(user).toBase64());

            // Wait for 334
            waitForResponse();
            if (responseCode != 334) { emit smtpError(AuthenticationFailedError); return false; }

            // Send the password in base64
            sendMessage(QByteArray().append(password).toBase64());

            // Wait for the server's responce
            waitForResponse();

            // If the response is not 235 then the authentication was faild
            if (responseCode != 235)
            {
                emit smtpError(AuthenticationFailedError);
                return false;
            }
        }
    }
    catch (ResponseTimeoutException e)
    {
        // Responce Timeout exceeded
        emit smtpError(AuthenticationFailedError);
        return false;
    }
    catch (SendMessageTimeoutException)
    {
	// Send Timeout exceeded
        emit smtpError(AuthenticationFailedError);
        return false;
    }

    return true;
}
示例#17
0
bool SmtpClient::sendMail(MimeMessage& email)
{
    try
    {
        // Send the MAIL command with the sender
        sendMessage("MAIL FROM: <" + email.getSender().getAddress() + ">");

        waitForResponse();

        if (responseCode != 250) return false;

        // Send RCPT command for each recipient
        QList<EmailAddress*>::const_iterator it, itEnd;
        // To (primary recipients)
        for (it = email.getRecipients().begin(), itEnd = email.getRecipients().end();
             it != itEnd; ++it)
        {
            sendMessage("RCPT TO: <" + (*it)->getAddress() + ">");
            waitForResponse();

            if (responseCode != 250) return false;
        }

        // Cc (carbon copy)
        for (it = email.getRecipients(MimeMessage::Cc).begin(), itEnd = email.getRecipients(MimeMessage::Cc).end();
             it != itEnd; ++it)
        {
            sendMessage("RCPT TO: <" + (*it)->getAddress() + ">");
            waitForResponse();

            if (responseCode != 250) return false;
        }

        // Bcc (blind carbon copy)
        for (it = email.getRecipients(MimeMessage::Bcc).begin(), itEnd = email.getRecipients(MimeMessage::Bcc).end();
             it != itEnd; ++it)
        {
            sendMessage("RCPT TO: <" + (*it)->getAddress() + ">");
            waitForResponse();

            if (responseCode != 250) return false;
        }
        // Send DATA command
        sendMessage("DATA");
        waitForResponse();

        if (responseCode != 354) return false;

        sendMessage(email.toString());

        // Send \r\n.\r\n to end the mail data
        sendMessage(".");

        waitForResponse();

        if (responseCode != 250) return false;
    }
    catch (ResponseTimeoutException)
    {
        return false;
    }
    catch (SendMessageTimeoutException)
    {
        return false;
    }

    return true;
}
示例#18
0
int FontInstInterface::reconfigure()
{
    KFI_DBUG;
    itsInterface->reconfigure(getpid(), false);
    return waitForResponse();
}