account.cpp 18.2 KB
Newer Older
1
/*
2
 *  Copyright (C) 2004-2015 Savoir-faire Linux Inc.
3 4
 *
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
5
 *  Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
6
 *  Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com>
7 8 9
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
10
 *  the Free Software Foundation; either version 3 of the License, or
11 12 13 14 15 16 17 18 19
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
20
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
21
 */
22

23 24 25
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
26
#include "account.h"
27

28
#include <algorithm>
29
#include <iterator>
30
#include <mutex>
31

Adrien Béraud's avatar
Adrien Béraud committed
32
#ifdef RING_VIDEO
33
#include "libav_utils.h"
34
#endif
35

36
#include "logger.h"
37 38
#include "manager.h"

39 40 41 42 43 44 45
#if HAVE_DHT
#include <opendht/rng.h>
using random_device = dht::crypto::random_device;
#else
using random_device = std::random_device;
#endif

46
#include "client/ring_signal.h"
47
#include "account_schema.h"
48
#include "string_utils.h"
49
#include "config/yamlparser.h"
50
#include "system_codec_container.h"
51
#include "ice_transport.h"
52

53 54
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
55
#include <yaml-cpp/yaml.h>
56
#pragma GCC diagnostic pop
57

58
#include "upnp/upnp_control.h"
59
#include "ip_utils.h"
60
#include "intrin.h"
61
#include "dring/account_const.h"
62

63 64
namespace ring {

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
const char * const Account::ALL_CODECS_KEY                = "allCodecs";
const char * const Account::VIDEO_CODEC_ENABLED           = "enabled";
const char * const Account::VIDEO_CODEC_NAME              = "name";
const char * const Account::VIDEO_CODEC_PARAMETERS        = "parameters";
const char * const Account::VIDEO_CODEC_BITRATE           = "bitrate";
const char * const Account::RINGTONE_PATH_KEY             = "ringtonePath";
const char * const Account::RINGTONE_ENABLED_KEY          = "ringtoneEnabled";
const char * const Account::VIDEO_ENABLED_KEY             = "videoEnabled";
const char * const Account::DISPLAY_NAME_KEY              = "displayName";
const char * const Account::ALIAS_KEY                     = "alias";
const char * const Account::TYPE_KEY                      = "type";
const char * const Account::ID_KEY                        = "id";
const char * const Account::USERNAME_KEY                  = "username";
const char * const Account::AUTHENTICATION_USERNAME_KEY   = "authenticationUsername";
const char * const Account::PASSWORD_KEY                  = "password";
const char * const Account::HOSTNAME_KEY                  = "hostname";
const char * const Account::ACCOUNT_ENABLE_KEY            = "enable";
const char * const Account::ACCOUNT_AUTOANSWER_KEY        = "autoAnswer";
const char * const Account::ACCOUNT_ACTIVE_CALL_LIMIT_KEY = "activeCallLimit";
const char * const Account::MAILBOX_KEY                   = "mailbox";
const char * const Account::DEFAULT_USER_AGENT            = PACKAGE_NAME "/" PACKAGE_VERSION;
const char * const Account::USER_AGENT_KEY                = "useragent";
const char * const Account::HAS_CUSTOM_USER_AGENT_KEY     = "hasCustomUserAgent";
const char * const Account::PRESENCE_MODULE_ENABLED_KEY   = "presenceModuleEnabled";
const char * const Account::UPNP_ENABLED_KEY              = "upnpEnabled";
90

91
Account::Account(const std::string &accountID)
92
    : accountID_(accountID)
93 94 95
    , username_()
    , hostname_()
    , alias_()
96
    , enabled_(true)
97
    , autoAnswerEnabled_(false)
98
    , registrationState_(RegistrationState::UNREGISTERED)
99 100
    , systemCodecContainer_(getSystemCodecContainer())
    , accountCodecInfoList_()
101
    , ringtonePath_("")
102 103
    , ringtoneEnabled_(true)
    , displayName_("")
104
    , userAgent_(DEFAULT_USER_AGENT)
105
    , hasCustomUserAgent_(false)
106
    , mailBox_()
107
    , upnp_(new upnp::Controller())
Julien Bonjean's avatar
Julien Bonjean committed
108
{
109
    random_device rdev;
110 111 112
    std::seed_seq seed {rdev(), rdev()};
    rand_.seed(seed);

113
    // Initialize the codec order, used when creating a new account
114
    loadDefaultCodecs();
115
    #ifdef __ANDROID__
Adrien Béraud's avatar
Adrien Béraud committed
116
        ringtonePath_ = "/data/data/cx.ring/files/ringtones/konga.ul";
117
    #else
Adrien Béraud's avatar
Adrien Béraud committed
118
        ringtonePath_ = "/usr/share/ring/ringtones/konga.ul";
119
    #endif
120 121
}

Julien Bonjean's avatar
Julien Bonjean committed
122
Account::~Account()
123
{}
124

125
void
126
Account::attachCall(const std::string& id)
127 128 129 130 131
{
    callIDSet_.insert(id);
}

void
132
Account::detachCall(const std::string& id)
133 134 135 136
{
    callIDSet_.erase(id);
}

137 138 139
void
Account::freeAccount()
{
140 141
    for (const auto& id : callIDSet_)
        Manager::instance().hangupCall(id);
142
    doUnregister();
143 144
}

145
void
146
Account::setRegistrationState(RegistrationState state, unsigned detail_code, const std::string& detail_str)
Julien Bonjean's avatar
Julien Bonjean committed
147
{
148 149
    if (state != registrationState_) {
        registrationState_ = state;
Emmanuel Milou's avatar
Emmanuel Milou committed
150
        // Notify the client
151 152
        emitSignal<DRing::ConfigurationSignal::RegistrationStateChanged>(
            accountID_,
153
            mapStateNumberToString(registrationState_),
154 155 156 157 158 159
            detail_code,
            detail_str);

        emitSignal<DRing::ConfigurationSignal::VolatileDetailsChanged>(
            accountID_,
            getVolatileAccountDetails());
Emmanuel Milou's avatar
Emmanuel Milou committed
160
    }
161
}
162

163 164
void
Account::loadDefaultCodecs()
Julien Bonjean's avatar
Julien Bonjean committed
165
{
166 167 168 169
    // default codec are system codecs
    auto systemCodecList = systemCodecContainer_->getSystemCodecInfoList();

    for (const auto& systemCodec: systemCodecList) {
170 171
        // As defined in SDP RFC, only select a codec if he can encode and decode
        if ((systemCodec->codecType & CODEC_ENCODER_DECODER) != CODEC_ENCODER_DECODER)
172 173 174 175 176 177 178 179 180
            continue;

        if (systemCodec->mediaType & MEDIA_AUDIO) {
            // we are sure of our downcast type : use static_pointer_cast
            auto audioCodec = std::static_pointer_cast<SystemAudioCodecInfo>(systemCodec);
            // instantiate AccountAudioCodecInfo initialized with our system codec
            auto codec = std::make_shared <AccountAudioCodecInfo>(*audioCodec);
            accountCodecInfoList_.push_back(codec);
        }
181

182 183 184 185 186 187 188 189
        if (systemCodec->mediaType & MEDIA_VIDEO) {
            // we are sure of our downcast type : use static_pointer_cast
            auto videoCodec = std::static_pointer_cast<SystemVideoCodecInfo>(systemCodec);
            // instantiate AccountVideoCodecInfo initialized with our system codec
            auto codec = std::make_shared<AccountVideoCodecInfo>(*videoCodec);
            accountCodecInfoList_.push_back(codec);
        }
    }
190
}
191

192 193 194 195 196 197 198 199 200 201 202
// Convert a list of payloads in a special format, readable by the server.
// Required format: payloads separated by slashes.
// @return std::string The serializable string
static std::string
join_string(const std::vector<unsigned> &v)
{
    std::ostringstream os;
    std::copy(std::begin(v), std::end(v), std::ostream_iterator<unsigned>(os, "/"));
    return os.str();
}

203
void
204
Account::serialize(YAML::Emitter& out)
205
{
206 207
    const auto& activeCodecs = join_string(getActiveAccountCodecInfoIdList(MEDIA_ALL));

208 209 210 211
    out << YAML::Key << ID_KEY << YAML::Value << accountID_;
    out << YAML::Key << ALIAS_KEY << YAML::Value << alias_;
    out << YAML::Key << ACCOUNT_ENABLE_KEY << YAML::Value << enabled_;
    out << YAML::Key << TYPE_KEY << YAML::Value << getAccountType();
212
    out << YAML::Key << ALL_CODECS_KEY << YAML::Value << activeCodecs;
213 214
    out << YAML::Key << MAILBOX_KEY << YAML::Value << mailBox_;
    out << YAML::Key << ACCOUNT_AUTOANSWER_KEY << YAML::Value << autoAnswerEnabled_;
215
    out << YAML::Key << ACCOUNT_ACTIVE_CALL_LIMIT_KEY << YAML::Value << activeCallLimit_;
216 217 218 219 220 221 222
    out << YAML::Key << RINGTONE_ENABLED_KEY << YAML::Value << ringtoneEnabled_;
    out << YAML::Key << RINGTONE_PATH_KEY << YAML::Value << ringtonePath_;
    out << YAML::Key << HAS_CUSTOM_USER_AGENT_KEY << YAML::Value << hasCustomUserAgent_;
    out << YAML::Key << USER_AGENT_KEY << YAML::Value << userAgent_;
    out << YAML::Key << USERNAME_KEY << YAML::Value << username_;
    out << YAML::Key << DISPLAY_NAME_KEY << YAML::Value << displayName_;
    out << YAML::Key << HOSTNAME_KEY << YAML::Value << hostname_;
223
    out << YAML::Key << UPNP_ENABLED_KEY << YAML::Value << upnpEnabled_;
224 225
}

226
void
227
Account::unserialize(const YAML::Node& node)
228
{
229 230
    using yaml_utils::parseValue;

231 232 233 234
    parseValue(node, ALIAS_KEY, alias_);
    parseValue(node, ACCOUNT_ENABLE_KEY, enabled_);
    parseValue(node, USERNAME_KEY, username_);
    parseValue(node, ACCOUNT_AUTOANSWER_KEY, autoAnswerEnabled_);
235
    parseValue(node, ACCOUNT_ACTIVE_CALL_LIMIT_KEY, activeCallLimit_);
236 237 238 239
    //parseValue(node, PASSWORD_KEY, password_);

    parseValue(node, MAILBOX_KEY, mailBox_);

240 241 242 243
    std::string activeCodecs;
    parseValue(node, ALL_CODECS_KEY, activeCodecs);
    setActiveCodecs(split_string_to_unsigned(activeCodecs, '/'));

244 245 246 247 248 249 250
    parseValue(node, DISPLAY_NAME_KEY, displayName_);
    parseValue(node, HOSTNAME_KEY, hostname_);

    parseValue(node, HAS_CUSTOM_USER_AGENT_KEY, hasCustomUserAgent_);
    parseValue(node, USER_AGENT_KEY, userAgent_);
    parseValue(node, RINGTONE_PATH_KEY, ringtonePath_);
    parseValue(node, RINGTONE_ENABLED_KEY, ringtoneEnabled_);
251

252 253 254
    bool enabled;
    parseValue(node, UPNP_ENABLED_KEY, enabled);
    upnpEnabled_.store(enabled);
255 256
}

257 258
void
Account::setAccountDetails(const std::map<std::string, std::string> &details)
259 260
{
    // Account setting common to SIP and IAX
261
    parseString(details, Conf::CONFIG_ACCOUNT_ALIAS, alias_);
262
    parseString(details, Conf::CONFIG_ACCOUNT_DISPLAYNAME, displayName_);
263 264 265 266 267 268
    parseBool(details, Conf::CONFIG_ACCOUNT_ENABLE, enabled_);
    parseString(details, Conf::CONFIG_ACCOUNT_USERNAME, username_);
    parseString(details, Conf::CONFIG_ACCOUNT_HOSTNAME, hostname_);
    parseString(details, Conf::CONFIG_ACCOUNT_MAILBOX, mailBox_);
    parseString(details, Conf::CONFIG_ACCOUNT_USERAGENT, userAgent_);
    parseBool(details, Conf::CONFIG_ACCOUNT_AUTOANSWER, autoAnswerEnabled_);
269
    parseInt(details, DRing::Account::ConfProperties::ACTIVE_CALL_LIMIT, activeCallLimit_);
270 271 272
    parseBool(details, Conf::CONFIG_RINGTONE_ENABLED, ringtoneEnabled_);
    parseString(details, Conf::CONFIG_RINGTONE_PATH, ringtonePath_);
    parseBool(details, Conf::CONFIG_ACCOUNT_HAS_CUSTOM_USERAGENT, hasCustomUserAgent_);
273
    if (hasCustomUserAgent_)
274
        parseString(details, Conf::CONFIG_ACCOUNT_USERAGENT, userAgent_);
275 276
    else
        userAgent_ = DEFAULT_USER_AGENT;
277 278 279
    bool enabled;
    parseBool(details, Conf::CONFIG_UPNP_ENABLED, enabled);
    upnpEnabled_.store(enabled);
280 281
}

282 283
std::map<std::string, std::string>
Account::getAccountDetails() const
284
{
285 286
    return {
        {Conf::CONFIG_ACCOUNT_ALIAS,        alias_},
287
        {Conf::CONFIG_ACCOUNT_DISPLAYNAME,  displayName_},
288 289 290 291 292 293 294 295
        {Conf::CONFIG_ACCOUNT_ENABLE,       enabled_ ? TRUE_STR : FALSE_STR},
        {Conf::CONFIG_ACCOUNT_TYPE,         getAccountType()},
        {Conf::CONFIG_ACCOUNT_HOSTNAME,     hostname_},
        {Conf::CONFIG_ACCOUNT_USERNAME,     username_},
        {Conf::CONFIG_ACCOUNT_MAILBOX,      mailBox_},
        {Conf::CONFIG_ACCOUNT_USERAGENT,    hasCustomUserAgent_ ? userAgent_ : DEFAULT_USER_AGENT},
        {Conf::CONFIG_ACCOUNT_HAS_CUSTOM_USERAGENT, hasCustomUserAgent_ ? userAgent_ : DEFAULT_USER_AGENT},
        {Conf::CONFIG_ACCOUNT_AUTOANSWER,   autoAnswerEnabled_ ? TRUE_STR : FALSE_STR},
296
        {DRing::Account::ConfProperties::ACTIVE_CALL_LIMIT,   ring::to_string(activeCallLimit_)},
297 298 299 300
        {Conf::CONFIG_RINGTONE_ENABLED,     ringtoneEnabled_ ? TRUE_STR : FALSE_STR},
        {Conf::CONFIG_RINGTONE_PATH,        ringtonePath_},
        {Conf::CONFIG_UPNP_ENABLED,         upnpEnabled_ ? TRUE_STR : FALSE_STR},
    };
301 302
}

303 304
std::map<std::string, std::string>
Account::getVolatileAccountDetails() const
305
{
306 307 308
    return {
        {Conf::CONFIG_ACCOUNT_REGISTRATION_STATUS, mapStateNumberToString(registrationState_)}
    };
309 310
}

311
std::vector<unsigned>
312
Account::getActiveCodecs() const
313
{
314
    return getActiveAccountCodecInfoIdList(MEDIA_ALL);
315 316 317
}

void
318
Account::setActiveCodecs(const std::vector<unsigned>& list)
Julien Bonjean's avatar
Julien Bonjean committed
319
{
320
    // first clear the previously stored codecs
321
    // TODO: mutex to protect isActive
322
    desactivateAllMedia(MEDIA_ALL);
323

Emmanuel Milou's avatar
Emmanuel Milou committed
324
    // list contains the ordered payload of active codecs picked by the user for this account
325
    // we used the codec vector to save the order.
326 327
    uint16_t order = 1;
    for (const auto& item : list) {
328
        if (auto accCodec = searchCodecById(item, MEDIA_ALL)) {
329 330 331 332
            accCodec->isActive = true;
            accCodec->order = order;
            ++order;
        }
Emmanuel Milou's avatar
Emmanuel Milou committed
333 334
    }

335 336 337 338 339 340
    std::sort(std::begin(accountCodecInfoList_),
              std::end  (accountCodecInfoList_),
              [](std::shared_ptr<AccountCodecInfo> a,
                 std::shared_ptr<AccountCodecInfo> b) {
                  return a->order < b->order;
              });
341
}
342

343 344
std::string
Account::mapStateNumberToString(RegistrationState state)
345
{
346 347 348 349 350 351 352 353 354 355 356 357 358 359
#define CASE_STATE(X) case RegistrationState::X: \
                           return #X

    switch (state) {
        CASE_STATE(UNREGISTERED);
        CASE_STATE(TRYING);
        CASE_STATE(REGISTERED);
        CASE_STATE(ERROR_GENERIC);
        CASE_STATE(ERROR_AUTH);
        CASE_STATE(ERROR_NETWORK);
        CASE_STATE(ERROR_HOST);
        CASE_STATE(ERROR_SERVICE_UNAVAILABLE);
        CASE_STATE(ERROR_EXIST_STUN);
        CASE_STATE(ERROR_NOT_ACCEPTABLE);
360
        default:
361
            return DRing::Account::States::ERROR_GENERIC;
362
    }
363

364
#undef CASE_STATE
365
}
366

367
std::vector<unsigned>
368
Account::getDefaultCodecsId()
369
{
370
    return getSystemCodecContainer()->getSystemCodecInfoIdList(MEDIA_ALL);
371
}
372

373 374 375 376
std::map<std::string, std::string>
Account::getDefaultCodecDetails(const unsigned& codecId)
{
    auto codec = ring::getSystemCodecContainer()->searchCodecById(codecId, ring::MEDIA_ALL);
377
    if (codec) {
378 379 380 381 382 383 384 385 386
        if (codec->mediaType & ring::MEDIA_AUDIO) {
            auto audioCodec = std::static_pointer_cast<ring::SystemAudioCodecInfo>(codec);
            return audioCodec->getCodecSpecifications();
        }
        if (codec->mediaType & ring::MEDIA_VIDEO) {
            auto videoCodec = std::static_pointer_cast<ring::SystemVideoCodecInfo>(codec);
            return videoCodec->getCodecSpecifications();
        }
    }
387
    return {};
388 389
}

390 391 392 393 394 395
#define find_iter()                                    \
    const auto& iter = details.find(key);               \
    if (iter == details.end()) {                       \
        RING_ERR("Couldn't find key \"%s\"", key);     \
        return;                                        \
    }
396 397

void
398 399
Account::parseString(const std::map<std::string, std::string>& details,
                     const char* key, std::string& s)
400 401 402 403 404 405
{
    find_iter();
    s = iter->second;
}

void
406 407
Account::parseBool(const std::map<std::string, std::string>& details,
                   const char* key, bool &b)
408 409
{
    find_iter();
410
    b = iter->second == TRUE_STR;
411 412 413
}

#undef find_iter
414

415
/**
416 417
 * Get the UPnP IP (external router) address.
 * If use UPnP is set to false, the address will be empty.
418
 */
419
IpAddr
420 421
Account::getUPnPIpAddress() const
{
422
    std::lock_guard<std::mutex> lk(upnp_mtx);
423 424 425
    if (upnpEnabled_)
        return upnp_->getExternalIP();
    return {};
426 427
}

428
/**
429 430
 * returns whether or not UPnP is enabled and active_
 * ie: if it is able to make port mappings
431
 */
432
bool
433
Account::getUPnPActive(std::chrono::seconds timeout) const
434
{
435
    std::lock_guard<std::mutex> lk(upnp_mtx);
436
    if (upnpEnabled_)
437
        return upnp_->hasValidIGD(timeout);
438 439 440 441 442 443 444 445 446 447
    return false;
}

/*
 * private account codec searching functions
 *
 * */
std::shared_ptr<AccountCodecInfo>
Account::searchCodecById(unsigned codecId, MediaType mediaType)
{
448 449 450 451
    if (mediaType != MEDIA_NONE) {
        for (auto& codecIt: accountCodecInfoList_) {
            if ((codecIt->systemCodecInfo.id == codecId) &&
                (codecIt->systemCodecInfo.mediaType & mediaType ))
452
                return codecIt;
453
        }
454 455 456 457 458 459 460
    }
    return {};
}

std::shared_ptr<AccountCodecInfo>
Account::searchCodecByName(std::string name, MediaType mediaType)
{
461 462 463 464 465 466
    if (mediaType != MEDIA_NONE) {
        for (auto& codecIt: accountCodecInfoList_) {
            if ((codecIt->systemCodecInfo.name.compare(name) == 0) &&
                (codecIt->systemCodecInfo.mediaType & mediaType ))
                return codecIt;
        }
467 468 469 470 471 472 473
    }
    return {};
}

std::shared_ptr<AccountCodecInfo>
Account::searchCodecByPayload(unsigned payload, MediaType mediaType)
{
474 475 476 477 478 479
    if (mediaType != MEDIA_NONE) {
        for (auto& codecIt: accountCodecInfoList_) {
            if ((codecIt->payloadType == payload ) &&
                (codecIt->systemCodecInfo.mediaType & mediaType ))
                return codecIt;
        }
480 481 482
    }
    return {};
}
483

484 485 486
std::vector<unsigned>
Account::getActiveAccountCodecInfoIdList(MediaType mediaType) const
{
487 488 489
    if (mediaType == MEDIA_NONE)
        return {};

490 491 492 493 494 495 496 497 498 499 500 501
    std::vector<unsigned> idList;
    for (auto& codecIt: accountCodecInfoList_) {
        if ((codecIt->systemCodecInfo.mediaType & mediaType) &&
            (codecIt->isActive))
            idList.push_back(codecIt->systemCodecInfo.id);
    }
    return idList;
}

std::vector<unsigned>
Account::getAccountCodecInfoIdList(MediaType mediaType) const
{
502 503 504
    if (mediaType == MEDIA_NONE)
        return {};

505 506 507 508 509
    std::vector<unsigned> idList;
    for (auto& codecIt: accountCodecInfoList_) {
        if (codecIt->systemCodecInfo.mediaType & mediaType)
            idList.push_back(codecIt->systemCodecInfo.id);
    }
510

511 512 513 514 515 516
    return idList;
}

void
Account::desactivateAllMedia(MediaType mediaType)
{
517 518 519
    if (mediaType == MEDIA_NONE)
        return;

520 521 522 523 524 525 526
    for (auto& codecIt: accountCodecInfoList_) {
        if (codecIt->systemCodecInfo.mediaType & mediaType)
            codecIt->isActive = false;
    }
}

std::vector<std::shared_ptr<AccountCodecInfo>>
527
Account::getActiveAccountCodecInfoList(MediaType mediaType) const
528
{
529 530 531
    if (mediaType == MEDIA_NONE)
        return {};

532 533 534 535 536 537
    std::vector<std::shared_ptr<AccountCodecInfo>> accountCodecList;
    for (auto& codecIt: accountCodecInfoList_) {
        if ((codecIt->systemCodecInfo.mediaType & mediaType) &&
            (codecIt->isActive))
            accountCodecList.push_back(codecIt);
    }
538

539
    return accountCodecList;
540 541
}

542 543 544 545 546 547 548 549
const IceTransportOptions
Account::getIceOptions() const noexcept
{
    IceTransportOptions opts;
    opts.upnpEnable = getUPnPActive();
    return opts;
}

550
} // namespace ring