void SyncAccountCommand::RunImpl()
{
	try {
		if (!m_client.GetAccount().get()) {
			MojString err;
			err.format("Account is not loaded for '%s'", AsJsonString(
					m_client.GetAccountId()).c_str());
			throw MailException(err.data(), __FILE__, __LINE__);
		}

		m_account = m_client.GetAccount();
		if(m_account->HasPassword()) {
			m_accountId = m_account->GetAccountId();
			MojObject inboxFolderId = m_account->GetInboxFolderId();

			MojLogInfo(m_log, "Creating command to sync inbox emails");

			MojErr err = m_payload.put(EmailSchema::FOLDER_ID, inboxFolderId);
			ErrorToException(err);

			m_client.SyncFolder(m_payload);
		} else {
			MojLogInfo(m_log, "No password!  Sync aborted!");
		}

		Complete();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception", __FILE__, __LINE__));
	}
}
Example #2
0
void MailSender::rcvResponse(const MailString expected_response)
{
    int recv_bytes = 0;
    char response_buffer[MAX_BUFFER_SIZE];
    if ( (recv_bytes = recv(_socket, response_buffer, MAX_BUFFER_SIZE, 0)) < 0 )
    {
        throw MailException( 
            ErrorMessage::getInstance().response(expected_response)
        );
    }

	int nDstLen = 0;
	TCHAR *pRecv = M_A2T(response_buffer, recv_bytes, nDstLen);

    MailString response(pRecv, nDstLen);
	delete[] pRecv;
	MailCout << _T("[INFO]RECV(") << expected_response << _T("):" )
		<< response << std::endl;

    if ( response.substr(0, 3) != expected_response )
    {
        throw MailException( 
            ErrorMessage::getInstance().response(expected_response)
        );
    }
}
MojErr SmtpAccountDisableCommand::DeleteOutboxWatchResponse(MojObject& response, MojErr err)
{
	MojLogInfo(m_log, "SmtpAccountDisable removing outbox watch");

	try {
		if(err) {
			if(err == ENOENT) {
				MojLogWarning(m_log, "outbox watch activity doesn't exist");
			} else {
				ResponseToException(response, err);
			}
		}

		MojObject payload;
		payload.put("activityName", m_accountWatchActivityName);

		m_client.SendRequest(m_deleteAccountWatchResponseSlot, "com.palm.activitymanager", "cancel", payload);
	} catch (const std::exception& e) {
		m_msg->replyError(err, e.what());
		Failure(e);
	} catch (...) {
		MojString error;
		error.format("uncaught exception in %s", __PRETTY_FUNCTION__);
		m_msg->replyError(MojErrInternal, error.data());
		Failure(MailException("unknown exception in cancelling activities response", __FILE__, __LINE__));
	}

	return MojErrNone;
}
MojErr MovePopEmailsCommand::ActivityUpdate(Activity* activity, Activity::EventType event)
{
	try {
		switch (event) {
		case Activity::StartEvent:
			GetEmailsToMove();
			break;
		case Activity::CompleteEvent:
			m_activityUpdateSlot.cancel();
			m_activityErrorSlot.cancel();
			Complete();
			break;
		default:
			// do nothing

			break;
		}
	} catch (const std::exception& ex) {
		m_msg->replyError(MojErrInternal, ex.what());
		Failure(ex);
	} catch (...) {
		m_msg->replyError(MojErrInternal);
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
void MovePopEmailsCommand::RunImpl()
{
	CommandTraceFunction();
	try {

		if (!m_client.GetAccount().get()) {
			MojString err;
			err.format("Account is not loaded for '%s'", AsJsonString(
					m_client.GetAccountId()).c_str());
			throw MailException(err.data(), __FILE__, __LINE__);
		}

		MojErr err = m_payload.getRequired("accountId", m_accountId);
		ErrorToException(err);

		m_activity = ActivityParser::GetActivityFromPayload(m_payload);

		if (m_activity.get()) {
			m_activity->SetSlots(m_activityUpdateSlot, m_activityErrorSlot);
			m_activity->Adopt(m_client);
			return;
		} else {
			GetEmailsToMove();
		}
	} catch (const std::exception& ex) {
		m_msg->replyError(MojErrInternal, ex.what());
		Failure(ex);
	} catch (...) {
		MailException ex("unknown exception", __FILE__, __LINE__);
		m_msg->replyError(MojErrInternal, ex.what());
		Failure(ex);
	}
}
MojErr MovePopEmailsCommand::EmailsMovedResponse(MojObject& response, MojErr err)
{
	try {
		ErrorToException(err);

		ActivityBuilder ab;
		m_client.GetActivityBuilderFactory()->BuildMoveEmailsWatch(ab);
		m_activity->UpdateAndComplete(m_client, ab.GetActivityObject());

		m_msg->replySuccess();

		if (m_inboxEmailsMoved.size() > 0) {
			// add the list of UIDs into UidCache
			GetUidCache();
		} else {
			Complete();
		}
	} catch (const std::exception& ex) {
		m_msg->replyError(MojErrInternal, ex.what());
		Failure(ex);
	} catch (...) {
		m_msg->replyError(MojErrInternal);
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
void PopAccountUpdateCommand::Sync()
{
	try {
		if (m_callSyncFolderOnClient) {
			// remove activity from payload & pass no activity to SyncAccount
			bool activityFound = false;
			MojErr err = m_payload.del("$activity", activityFound);

			if (err == MojErrNone) {
				err = m_payload.putBool("force", true);
				ErrorToException(err);
				m_client.SyncAccount(m_payload);
			}
		}

		if(m_credentialsChanged) {
			NotifySmtp();
		} else {
			Done();
		}
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception", __FILE__, __LINE__));
	}
}
void PopAccountUpdateCommand::UpdateAccountWatchActivity()
{
	CommandTraceFunction();

	try {
		MojObject revPop;
		MojErr err = m_transportObj.getRequired("_revPop", revPop);
		ErrorToException(err);

		ActivityBuilder ab;
		m_activityBuilderFactory->BuildAccountPrefsWatch(ab, revPop);

		MojObject payload;
		err = payload.put("activity", ab.GetActivityObject());
		ErrorToException(err);
		err = payload.put("start", true);
		ErrorToException(err);
		err = payload.put("replace", true);
		ErrorToException(err);

		m_client.SendRequest(m_createActivitySlot, "com.palm.activitymanager", "create", payload);
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}
}
MojErr SmtpAccountDisableCommand::DeleteAccountWatchResponse(MojObject& response, MojErr err)
{
	MojLogInfo(m_log, "SmtpAccountDisable replying");

	try {
		if(err) {
			if(err == ENOENT) {
				MojLogWarning(m_log, "account watch activity doesn't exist");
			} else {
				ResponseToException(response, err);
			}
		}

		m_msg->replySuccess();
		Complete();
	} catch (const std::exception& e) {
		m_msg->replyError(err, e.what());
		Failure(e);
	} catch (...) {
		MojString error;
		error.format("uncaught exception in %s", __PRETTY_FUNCTION__);
		m_msg->replyError(MojErrInternal, error.data());
		Failure(MailException("unknown exception in cancelling activities response", __FILE__, __LINE__));
	}
	return MojErrNone;
}
Example #10
0
boost::shared_ptr<FileCacheClient> PopSession::GetFileCacheClient()
{
	if(m_fileCacheClient.get())
		return m_fileCacheClient;
	else
		throw MailException("no file cache client configured", __FILE__, __LINE__);
}
bool ImapSyncSessionCommand::PrepareToRun()
{
	CommandTraceFunction();

	if(!ImapSessionCommand::PrepareToRun()) {
		// Parent class isn't ready to let us run yet
		return false;
	}

	if(m_syncSessionReady) {
		return true;
	}

	try {
		if(m_session.GetClient().get() == NULL) {
			throw MailException("can't run sync session command without a client", __FILE__, __LINE__);
		}

		m_session.GetClient()->RequestSyncSession(m_folderId, this, m_syncSessionReadySlot);

		// SyncSessionReady will be called when the sync session is ready to run
	} catch(const exception& e) {
		Failure(e);
	} catch(...) {
		Failure(UNKNOWN_EXCEPTION);
	}

	return false;
}
Example #12
0
void ConnectCommand::RunImpl()
{
    CommandTraceFunction();

    try {
        const ImapLoginSettings& loginSettings = m_session.GetLoginSettings();

        std::string hostname = loginSettings.GetHostname();
        int port = loginSettings.GetPort();
        ImapLoginSettings::EncryptionType encryption = loginSettings.GetEncryption();

        if(hostname.empty() || port <= 0) {
            throw MailException("empty hostname or port", __FILE__, __LINE__);
        }

        MojLogInfo(m_log, "connecting to %s:%d%s on interface %s",
                   hostname.c_str(), port, (encryption == ImapLoginSettings::Encrypt_SSL) ? " with SSL" : "",
                   !m_bindAddress.empty() ? m_bindAddress.c_str() : "0.0.0.0");

        m_connection = SocketConnection::CreateSocket(hostname.c_str(), port,
                       (encryption == ImapLoginSettings::Encrypt_SSL), m_bindAddress);

        int connectTimeout = ImapConfig::GetConfig().GetConnectTimeout();

        if(connectTimeout) {
            m_connection->SetConnectTimeout(connectTimeout);
        }

        m_connection->Connect(m_connectedSlot);
    } catch(const exception& e) {
        ConnectFailure(e);
    }
}
MojErr AccountFinderCommand::GetPasswordResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		// check the result first
		ErrorToException(err);

		MojObject credentials;
		// Credentials object can be missing if the POP account is restored from
		// backup.  Checking for its existence before using it will prevent exception
		// to be thrown.
		bool exists = response.get("credentials", credentials);
		if (exists) {
			MojString password;
			err = credentials.getRequired("password", password);
			ErrorToException(err);

			m_account->SetPassword(password.data());
		} else {
			MojLogInfo(m_log, "The credentials of POP account '%s' are missing", AsJsonString(m_accountId).c_str());
		}

		// get the transport object
		GetPopAccount();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
Example #14
0
void IdleCommand::EndIdle()
{
	CommandTraceFunction();

	if(!m_endingIdle) {
		m_endingIdle = true;

		// Tell the server to break out of IDLE
		// It should respond by completing the original IDLE command request
		MojLogDebug(m_log, "sending DONE to break out of idle");

		try {
			if(m_session.GetOutputStream().get() != NULL) {
				m_session.GetOutputStream()->Write("DONE\r\n");
				m_session.GetOutputStream()->Flush();

				if(m_session.GetLineReader().get()) {
					// Give it 30 seconds to respond to the DONE
					m_session.GetLineReader()->SetTimeout(30);
				}
			} else {
				throw MailException("no connection output stream", __FILE__, __LINE__);
			}
		} CATCH_AS_FAILURE
	} else {
MojErr InsertEmailsCommand::ReserverEmailIdsResponse(MojObject& response, MojErr err)
{
	try
	{
		ErrorToException(err);

		MojLogDebug(m_log, "Got reserver ids response: %s", AsJsonString(response).c_str());
		MojObject idArray;
		err = response.getRequired("ids", idArray);
		ErrorToException(err);

		for (int ndx = 0; ndx < (int)m_emails->size(); ndx++) {
			MojObject id;
			idArray.at(ndx, id);

			PopEmail::PopEmailPtr emailPtr = m_emails->at(ndx);
			MojLogDebug(m_log, "Assigning id '%s' to email '%s'", AsJsonString(id).c_str(), emailPtr->GetServerUID().c_str());
			emailPtr->SetId(id);
		}

		SaveEmails();
	}
	catch (const std::exception& e) {
		MojLogError(m_log, "Exception in reserving email ID: '%s'", e.what());
		Failure(e);
	} catch (...) {
		MojLogError(m_log, "Unknown exception in reserving email ID");
		Failure(MailException("Unknown exception in reserving email ID", __FILE__, __LINE__));
		
	}

	return MojErrNone;
}
MojInt64 ImapSyncSessionCommand::GetLastSyncRev() const
{
	if(m_syncSession.get() != NULL)
		return m_syncSession->GetLastSyncRev();
	else
		throw MailException("no sync session available", __FILE__, __LINE__);
}
MojErr AccountFinderCommand::GetPopAccountResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		// check database result first
		ErrorToException(err);

		MojObject results;
		err = response.getRequired(_T("results"), results);
		ErrorToException(err);

		if (results.size() > 0) {
			MojObject transportObj;
			if (results.at(0, transportObj)) {
				PopAccountAdapter::GetPopAccount(m_accountObj, transportObj, *(m_account.get()));
			}
		}

		MojLogInfo(m_log, "Setting account to pop client");
		m_client.SetAccount(m_account);

		Complete();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
void ScheduleRetryCommand::RunImpl()
{
	try {
		if (!m_client.GetAccount().get()) {
			MojString err;
			err.format("Account is not loaded for '%s'", AsJsonString(
					m_client.GetAccountId()).c_str());
			throw MailException(err.data(), __FILE__, __LINE__);
		}

		ScheduleRetry();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception in scheduling POP account retry", __FILE__, __LINE__));
	}
}
void DownloadPartCommand::RunImpl()
{
	try {
		if (!m_client.GetAccount().get()) {
			MojString err;
			err.format("Account is not loaded for '%s'", AsJsonString(m_client.GetAccountId()).c_str());
			throw MailException(err.data(), __FILE__, __LINE__);
		}

		m_client.GetSession()->FetchEmail(m_emailId, m_partId, m_listener);
		Complete();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception in downloading email", __FILE__, __LINE__));
	}
}
Example #20
0
 MojErr Error(Activity*, Activity::ErrorType error, const std::exception& e)
 {
     if(m_expectError) {
         m_expectError = false;
     } else if(m_expect) {
         throw MailException("Unexpected error", __FILE__, __LINE__);
     }
     return MojErrNone;
 }
Example #21
0
 MojErr Update(Activity* activity, Activity::EventType event)
 {
     if(m_expectUpdate && event == m_expectEventType) {
         m_expectUpdate = false;
     } else if(m_expect) {
         throw MailException("Unexpected update", __FILE__, __LINE__);
     }
     return MojErrNone;
 }
void SaveEmailCommand::PrepareParts()
{
	MojErr err;

	err = m_email.getRequired(EmailSchema::PARTS, m_partsArray);
	ErrorToException(err);

	// Basic preflight to make sure the parts array is valid
	MojObject::ArrayIterator it;
	err = m_partsArray.arrayBegin(it);
	ErrorToException(err);

	for (; it != m_partsArray.arrayEnd(); ++it) {
		MojObject& part = *it;

		bool hasPath;
		MojString path;
		err = part.get(EmailSchema::Part::PATH, path, hasPath);
		ErrorToException(err);

		MojString type;
		err = part.getRequired(EmailSchema::Part::TYPE, type);
		ErrorToException(err);

		bool hasContent;
		MojString content;
		err = part.get("content", content, hasContent);
		ErrorToException(err);
		
		if(hasPath && hasContent) {
			throw MailException("part should have \"content\" or \"path\", not both", __FILE__, __LINE__);
		}
		
		if(!hasPath && !hasContent) {
			throw MailException("part has neither \"content\" nor \"path\"", __FILE__, __LINE__);
		}
	}

	// Point to the first part in the array
	err = m_partsArray.arrayBegin(m_partsIt);
	ErrorToException(err);

	CreateNextCacheObject();
}
void PopAccountEnableCommand::RunImpl()
{
	try {
		if (!m_client.GetAccount().get()) {
			MojString err;
			err.format("Account is not loaded for '%s'", AsJsonString(
					m_client.GetAccountId()).c_str());
			throw MailException(err.data(), __FILE__, __LINE__);
		}

		m_account = m_client.GetAccount();
		m_accountId = m_account->GetAccountId();
		FindSpecialFolders();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception in enabling POP account", __FILE__, __LINE__));
	}
}
Example #24
0
void MailSender::sendRequest(Operaion operation, 
                             const std::string content)
{
    std::cout << "[INFO]SEND:" << content << std::endl;

    if ( send(_socket, content.c_str(), content.length(), 0) < 0 )
    {
        throw MailException(
            ErrorMessage::getInstance().request(operation)
        );
    }
}
Example #25
0
void MailSender::rcvResponse(const std::string expected_response)
{
    int recv_bytes = 0;
    char response_buffer[MAX_BUFFER_SIZE];
    if ( (recv_bytes = recv(_socket, response_buffer, MAX_BUFFER_SIZE, 0)) < 0 )
    {
        throw MailException( 
            ErrorMessage::getInstance().response(expected_response)
        );
    }

    std::string response(response_buffer, recv_bytes);
    std::cout << "[INFO]RECV(" << expected_response << "):" 
              << response << std::endl;
    if ( response.substr(0, 3) != expected_response )
    {
        throw MailException( 
            ErrorMessage::getInstance().response(expected_response)
        );
    }
}
void SaveEmailCommand::RunImpl()
{
	try {
		GetAccount();
	} catch(const std::exception& e) {
		Error(e);
	} catch(...) {
		Error( MailException("unknown", __FILE__, __LINE__) );
	}
	
	return;
}
MojErr SyncFolderCommand::OutboxSyncResponse(MojObject& response, MojErr err) {
	try {
		ErrorToException(err);

		Complete();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
MojErr SyncFolderCommand::SyncSessionCompletedResponse() {
	try {
		// start another sync after previous sync completes
		StartFolderSync(m_activity);

		Complete();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
void PopAccountDeleteCommand::RunImpl()
{
	CommandTraceFunction();
	try {
		MojErr err = m_payload.getRequired("accountId", m_accountId);
		ErrorToException(err);
		m_dbInterface->DeleteItems(m_deletePopAccountSlot, PopAccountAdapter::POP_ACCOUNT_KIND, "accountId", m_accountId);
	} catch (const std::exception& e) {
		m_msg->replyError(MojErrInternal);
		Failure(e);
	} catch (...) {
		m_msg->replyError(MojErrInternal);
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}
}
Example #30
0
void MailSender::hello()
{
    char local_host[MAX_BUFFER_SIZE];
    if ( gethostname(local_host, MAX_BUFFER_SIZE) != 0 )
    {
        throw MailException("Get local host name error");
    }

    std::string msg;

    msg  = "HELO ";
    msg += std::string(local_host) + "\r\n";
    sendRequest(send_helo_cmd, msg);
    rcvResponse("250");
}