<commit_before>/***

Copyright 2013-2016 <NAME>
Copyright 2014-2016 Surevine Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

***/

#include "router.h"
#include "dns.h"
#include "xmlstream.h"
#include "netsession.h"
#include "log.h"
#include "config.h"

#include <unordered_map>
#include <algorithm>

using namespace Metre;

Route::Route(Jid const &from, Jid const &to) : m_local(from), m_domain(to), onNamesCollated() {
    METRE_LOG(Metre::Log::DEBUG, "Route created, local is " << m_local.domain() << " remote is " << m_domain.domain());
}

namespace {
    bool check_verify(Route &r, std::shared_ptr<NetSession> const &vrfy) {
        if (vrfy) {
            if (vrfy->xml_stream().auth_ready()) {
                r.SessionDialback(vrfy->xml_stream());
                return true;
            } else {
                vrfy->xml_stream().onAuthReady.connect(&r, &Route::SessionDialback);
            }
        }
        return false;
    }


    bool check_to(Route &r, std::shared_ptr<NetSession> const &to) {
        if (to) {
            switch (to->xml_stream().s2s_auth_pair(r.local(), r.domain(), OUTBOUND)) {
                case XMLStream::AUTHORIZED:
                    r.SessionAuthenticated(to->xml_stream());
                    return true;
                default:
                    if (!to->xml_stream().auth_ready()) {
                        to->xml_stream().onAuthReady.connect(&r, &Route::SessionDialback);
                    } else {
                        /// Send a dialback request or something.
                        std::string key = Config::config().dialback_key(to->xml_stream().stream_id(), r.local(),
                                                                        r.domain());
                        rapidxml::xml_document<> d;
                        auto dbr = d.allocate_node(rapidxml::node_element, "db:result");
                        dbr->append_attribute(d.allocate_attribute("to", r.domain().c_str()));
                        dbr->append_attribute(d.allocate_attribute("from", r.local().c_str()));
                        dbr->value(key.c_str(), key.length());
                        d.append_node(dbr);
                        to->xml_stream().send(d);
                        to->xml_stream().s2s_auth_pair(r.local(), r.domain(), OUTBOUND, XMLStream::REQUESTED);
                    }
                    // Fallthrough
                case XMLStream::REQUESTED:
                    to->xml_stream().onAuthenticated.connect(&r, &Route::SessionAuthenticated);
            }
        }
        return false;
    }
}

void Route::transmit(std::unique_ptr<DB::Verify> &&v) {
    auto vrfy = m_vrfy.lock();
    if (check_verify(*this, vrfy)) {
        if (!m_dialback.empty()) {
            v->freeze();
            m_dialback.push_back(std::move(v));
            return;
        } else {
            vrfy->xml_stream().send(std::move(v));
        }
    } else {
        // TODO Look for an existing session and use that.
        // Otherwise, start SRV lookups.
        v->freeze();
        m_dialback.push_back(std::move(v));
        Config::config().domain(m_domain.domain()).SrvLookup(m_domain.domain()).connect(this, &Route::SrvResult, true);
    }

}

void Route::bounce_dialback(bool timeout) {
    // TODO : verify->failed(timeout); // Or something.
}

void Route::bounce_stanzas(Stanza::Error e) {
    for (auto &stanza : m_stanzas) {
        if (stanza->type_str() && *stanza->type_str() == "error") continue;
        auto bounce = stanza->create_bounce(e);
        RouteTable::routeTable(bounce->from()).route(bounce->to())->transmit(std::move(bounce));
    }
    m_stanzas.clear();
    m_srv_valid = m_a_valid = false;
}

void Route::queue(std::unique_ptr<Stanza> &&s) {
    s->freeze();
    if (m_stanzas.empty())
        Router::defer([this]() {
            bounce_stanzas(Stanza::remote_server_timeout);
        }, Config::config().domain(m_domain.domain()).stanza_timeout());
    m_stanzas.push_back(std::move(s));
    METRE_LOG(Metre::Log::DEBUG, "Queued stanza for " << m_local.domain() << "=>" << m_domain.domain());
}

void Route::transmit(std::unique_ptr<Stanza> &&s) {
    auto to = m_to.lock();
    if (check_to(*this, to)) {
        if (!m_stanzas.empty()) {
            METRE_LOG(Metre::Log::DEBUG,
                      "Queuing stanza (backlog) for " << m_local.domain() << "=>" << m_domain.domain());
            queue(std::move(s));
            return;
        } else {
            to->xml_stream().send(std::move(s));
        }
    } else if (!to) {
        if (!m_vrfy.expired()) {
            std::shared_ptr<NetSession> vrfy(m_vrfy);
            m_to = vrfy;
            transmit(std::move(s)); // Retry<commit_msg>Close sessions when bouncing stanzas<commit_after>/***

Copyright 2013-2016 <NAME>
Copyright 2014-2016 Surevine Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

***/

#include "router.h"
#include "dns.h"
#include "xmlstream.h"
#include "netsession.h"
#include "log.h"
#include "config.h"

#include <unordered_map>
#include <algorithm>

using namespace Metre;

Route::Route(Jid const &from, Jid const &to) : m_local(from), m_domain(to), onNamesCollated() {
    METRE_LOG(Metre::Log::DEBUG, "Route created, local is " << m_local.domain() << " remote is " << m_domain.domain());
}

namespace {
    bool check_verify(Route &r, std::shared_ptr<NetSession> const &vrfy) {
        if (vrfy) {
            if (vrfy->xml_stream().auth_ready()) {
                r.SessionDialback(vrfy->xml_stream());
                return true;
            } else {
                vrfy->xml_stream().onAuthReady.connect(&r, &Route::SessionDialback);
            }
        }
        return false;
    }


    bool check_to(Route &r, std::shared_ptr<NetSession> const &to) {
        if (to) {
            switch (to->xml_stream().s2s_auth_pair(r.local(), r.domain(), OUTBOUND)) {
                case XMLStream::AUTHORIZED:
                    r.SessionAuthenticated(to->xml_stream());
                    return true;
                default:
                    if (!to->xml_stream().auth_ready()) {
                        to->xml_stream().onAuthReady.connect(&r, &Route::SessionDialback);
                    } else {
                        /// Send a dialback request or something.
                        std::string key = Config::config().dialback_key(to->xml_stream().stream_id(), r.local(),
                                                                        r.domain());
                        rapidxml::xml_document<> d;
                        auto dbr = d.allocate_node(rapidxml::node_element, "db:result");
                        dbr->append_attribute(d.allocate_attribute("to", r.domain().c_str()));
                        dbr->append_attribute(d.allocate_attribute("from", r.local().c_str()));
                        dbr->value(key.c_str(), key.length());
                        d.append_node(dbr);
                        to->xml_stream().send(d);
                        to->xml_stream().s2s_auth_pair(r.local(), r.domain(), OUTBOUND, XMLStream::REQUESTED);
                    }
                    // Fallthrough
                case XMLStream::REQUESTED:
                    to->xml_stream().onAuthenticated.connect(&r, &Route::SessionAuthenticated);
            }
        }
        return false;
    }
}

void Route::queue(std::unique_ptr<DB::Verify> &&s) {
    s->freeze();
    if (m_dialback.empty())
        Router::defer([this]() {
            bounce_dialback(true);
        }, Config::config().domain(m_domain.domain()).stanza_timeout());
    m_dialback.push_back(std::move(s));
    METRE_LOG(Metre::Log::DEBUG, "Queued stanza for " << m_local.domain() << "=>" << m_domain.domain());
}

void Route::transmit(std::unique_ptr<DB::Verify> &&v) {
    auto vrfy = m_vrfy.lock();
    if (check_verify(*this, vrfy)) {
        if (!m_dialback.empty()) {
            queue(std::move(v));
            return;
        } else {
            vrfy->xml_stream().send(std::move(v));
        }
    } else {
        // TODO Look for an existing session and use that.
        // Otherwise, start SRV lookups.
        queue(std::move(v));
        Config::config().domain(m_domain.domain()).SrvLookup(m_domain.domain()).connect(this, &Route::SrvResult, true);
    }

}

void Route::bounce_dialback(bool timeout) {
    m_srv_valid = m_a_valid = false;
    auto verify = m_vrfy.lock();
    if (verify) {
        verify->close();
        m_vrfy.reset();
    }
}

void Route::bounce_stanzas(Stanza::Error e) {
    for (auto &stanza : m_stanzas) {
        if (stanza->type_str() && *stanza->type_str() == "error") continue;
        auto bounce = stanza->create_bounce(e);
        RouteTable::routeTable(bounce->from()).route(bounce->to())->transmit(std::move(bounce));
    }
    m_stanzas.clear();
    m_srv_valid = m_a_valid = false;
    auto to = m_to.lock();
    if (to) {
        to->close();
        m_to.reset();
    }
}

void Route::queue(std::unique_ptr<Stanza> &&s) {
    s->freeze();
    if (m_stanzas.empty())
        Router::defer([this]() {
            bounce_stanzas(Stanza::remote_server_timeout);
        }, Config::config().domain(m_domain.domain()).stanza_timeout());
    m_stanzas.push_back(std::move(s));
    METRE_LOG(Metre::Log::DEBUG, "Queued stanza for " << m_local.domain() << "=>" << m_domain.domain());
}

void Route::transmit(std::unique_ptr<Stanza> &&s) {
    auto to = m_to.lock();
    if (check_to(*this, to)) {
        if (!m_stanzas.empty()) {
            METRE_LOG(Metre::Log::DEBUG,
                      "Queuing stanza (backlog) for " << m_local.domain() << "=>" << m_domain.domain());
            queue(std::move(s));
            return;
        } else {
            to->xml_stream().send(std::move(s));
        }
    } else if (!to) {
        if (!m_vrfy.expired()) {
            std::shared_ptr<NetSession> vrfy(m_vrfy);
            m_to = vrfy;
            transmit(std::move(s)); // Retry
{'fraction_non_alphanumeric': 0.14106556687147548, 'fraction_numerical': 0.003030047975759616, 'mean_word_length': 2.3958273792512146, 'pattern_counts': {'":': 0, '<': 66, '<?xml version=': 0, '>': 81, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 34}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '565580', 'n_tokens_mistral': 3683, 'n_tokens_neox': 3556, 'n_words': 822}