~ubuntu-branches/ubuntu/trusty/sflphone/trusty

« back to all changes in this revision

Viewing changes to daemon/src/sip/sipaccount.cpp

  • Committer: Package Import Robot
  • Author(s): Mark Purcell
  • Date: 2014-01-28 18:23:36 UTC
  • mfrom: (4.3.4 sid)
  • Revision ID: package-import@ubuntu.com-20140128182336-jrsv0k9u6cawc068
Tags: 1.3.0-1
* New upstream release 
  - Fixes "New Upstream Release" (Closes: #735846)
  - Fixes "Ringtone does not stop" (Closes: #727164)
  - Fixes "[sflphone-kde] crash on startup" (Closes: #718178)
  - Fixes "sflphone GUI crashes when call is hung up" (Closes: #736583)
* Build-Depends: ensure GnuTLS 2.6
  - libucommon-dev (>= 6.0.7-1.1), libccrtp-dev (>= 2.0.6-3)
  - Fixes "FTBFS Build-Depends libgnutls{26,28}-dev" (Closes: #722040)
* Fix "boost 1.49 is going away" unversioned Build-Depends: (Closes: #736746)
* Add Build-Depends: libsndfile-dev, nepomuk-core-dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*
2
 
 *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
 
2
 *  Copyright (C) 2004-2013 Savoir-Faire Linux Inc.
3
3
*
4
4
*  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
5
5
*  Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com>
42
42
#include "config/yamlemitter.h"
43
43
#include "logger.h"
44
44
#include "manager.h"
 
45
 
 
46
#ifdef SFL_PRESENCE
 
47
#include "sippresence.h"
 
48
#include "client/configurationmanager.h"
 
49
#endif
 
50
 
 
51
#include <unistd.h>
45
52
#include <pwd.h>
46
53
#include <sstream>
47
54
#include <algorithm>
48
55
#include <cstdlib>
 
56
#include <array>
 
57
#include <memory>
 
58
 
49
59
 
50
60
#ifdef SFL_VIDEO
51
61
#include "video/libav_utils.h"
52
62
#endif
53
63
 
 
64
 
54
65
const char * const SIPAccount::IP2IP_PROFILE = "IP2IP";
55
66
const char * const SIPAccount::OVERRTP_STR = "overrtp";
56
67
const char * const SIPAccount::SIPINFO_STR = "sipinfo";
57
68
const char * const SIPAccount::ACCOUNT_TYPE = "SIP";
58
69
 
59
70
namespace {
60
 
    const int MIN_REGISTRATION_TIME = 60;
61
 
    const int DEFAULT_REGISTRATION_TIME = 3600;
62
 
    const char *const TRUE_STR = "true";
63
 
    const char *const FALSE_STR = "false";
 
71
const int MIN_REGISTRATION_TIME = 60;
 
72
const int DEFAULT_REGISTRATION_TIME = 3600;
 
73
const char *const VALID_TLS_METHODS[] = {"Default", "TLSv1", "SSLv3", "SSLv23"};
 
74
const char *const VALID_SRTP_KEY_EXCHANGES[] = {"", "sdes", "zrtp"};
64
75
}
65
76
 
66
 
SIPAccount::SIPAccount(const std::string& accountID)
 
77
// we force RTP ports to be even, so we only need HALF_MAX_PORT booleans
 
78
bool SIPAccount::portsInUse_[HALF_MAX_PORT];
 
79
 
 
80
SIPAccount::SIPAccount(const std::string& accountID, bool presenceEnabled)
67
81
    : Account(accountID)
68
82
    , transport_(NULL)
 
83
    , auto_rereg_()
69
84
    , credentials_()
70
85
    , regc_(NULL)
71
86
    , bRegister_(false)
80
95
    , transportType_(PJSIP_TRANSPORT_UNSPECIFIED)
81
96
    , cred_()
82
97
    , tlsSetting_()
83
 
    , ciphers(100)
 
98
    , ciphers_(100)
84
99
    , stunServerName_()
85
100
    , stunPort_(PJ_STUN_PORT)
86
101
    , dtmfType_(OVERRTP_STR)
87
 
    , tlsEnable_(FALSE_STR)
 
102
    , tlsEnable_(false)
88
103
    , tlsCaListFile_()
89
104
    , tlsCertificateFile_()
90
105
    , tlsPrivateKeyFile_()
97
112
    , tlsRequireClientCertificate_(true)
98
113
    , tlsNegotiationTimeoutSec_("2")
99
114
    , tlsNegotiationTimeoutMsec_("0")
100
 
    , stunServer_("stun.sflphone.org")
 
115
    , stunServer_("")
101
116
    , stunEnabled_(false)
102
117
    , srtpEnabled_(false)
103
 
    , srtpKeyExchange_("sdes")
 
118
    , srtpKeyExchange_("")
104
119
    , srtpFallback_(false)
105
120
    , zrtpDisplaySas_(true)
106
121
    , zrtpDisplaySasOnce_(false)
114
129
    , receivedParameter_("")
115
130
    , rPort_(-1)
116
131
    , via_addr_()
 
132
    , contactBuffer_()
 
133
    , contact_{contactBuffer_, 0}
 
134
    , contactRewriteMethod_(2)
 
135
    , allowViaRewrite_(true)
 
136
    , allowContactRewrite_(1)
 
137
    , via_tp_(nullptr)
 
138
    , audioPortRange_({16384, 32766})
 
139
#ifdef SFL_VIDEO
 
140
    , videoPortRange_({49152, (MAX_PORT) - 2})
 
141
#endif
 
142
#ifdef SFL_PRESENCE
 
143
    , presence_(presenceEnabled ? new SIPPresence(this) : 0)
 
144
#endif
117
145
{
118
146
    via_addr_.host.ptr = 0;
119
147
    via_addr_.host.slen = 0;
123
151
        alias_ = IP2IP_PROFILE;
124
152
}
125
153
 
 
154
 
 
155
SIPAccount::~SIPAccount()
 
156
{
 
157
#ifdef SFL_PRESENCE
 
158
    delete presence_;
 
159
#endif
 
160
}
 
161
 
 
162
 
 
163
namespace {
 
164
std::array<std::unique_ptr<Conf::ScalarNode>, 2>
 
165
serializeRange(Conf::MappingNode &accountMap, const char *minKey, const char *maxKey, const std::pair<uint16_t, uint16_t> &range)
 
166
{
 
167
    using namespace Conf;
 
168
    std::array<std::unique_ptr<ScalarNode>, 2> result;
 
169
 
 
170
    std::ostringstream os;
 
171
    os << range.first;
 
172
    result[0].reset(new ScalarNode(os.str()));
 
173
    os.str("");
 
174
    accountMap.setKeyValue(minKey, result[0].get());
 
175
 
 
176
    os << range.second;
 
177
    ScalarNode portMax(os.str());
 
178
    result[1].reset(new ScalarNode(os.str()));
 
179
    accountMap.setKeyValue(maxKey, result[1].get());
 
180
    return result;
 
181
}
 
182
 
 
183
 
 
184
void updateRange(int min, int max, std::pair<uint16_t, uint16_t> &range)
 
185
{
 
186
    if (min > 0 and (max > min) and max <= MAX_PORT - 2) {
 
187
        range.first = min;
 
188
        range.second = max;
 
189
    }
 
190
}
 
191
 
 
192
void
 
193
unserializeRange(const Conf::YamlNode &mapNode, const char *minKey, const char *maxKey, std::pair<uint16_t, uint16_t> &range)
 
194
{
 
195
    int tmpMin = 0;
 
196
    int tmpMax = 0;
 
197
    mapNode.getValue(minKey, &tmpMin);
 
198
    mapNode.getValue(maxKey, &tmpMax);
 
199
    updateRange(tmpMin, tmpMax, range);
 
200
}
 
201
}
 
202
 
 
203
 
 
204
 
126
205
void SIPAccount::serialize(Conf::YamlEmitter &emitter)
127
206
{
128
207
    using namespace Conf;
151
230
    ScalarNode serviceRoute(serviceRoute_);
152
231
    ScalarNode keepAliveEnabled(keepAliveEnabled_);
153
232
 
 
233
#ifdef SFL_PRESENCE
 
234
    std::string pres(presence_ and getPresence()->isEnabled() ? Conf::TRUE_STR : Conf::FALSE_STR);
 
235
    ScalarNode presenceEnabled(pres);
 
236
    std::string presPub(presence_ and getPresence()->isSupported(PRESENCE_FUNCTION_PUBLISH) ? Conf::TRUE_STR : Conf::FALSE_STR);
 
237
    ScalarNode presencePublish(presPub);
 
238
    std::string presSub(presence_ and getPresence()->isSupported(PRESENCE_FUNCTION_SUBSCRIBE) ? Conf::TRUE_STR : Conf::FALSE_STR);
 
239
    ScalarNode presenceSubscribe(presSub);
 
240
#endif
 
241
 
154
242
    ScalarNode mailbox(mailBox_);
155
243
    ScalarNode publishAddr(publishedIpAddress_);
156
244
    std::stringstream publicportstr;
163
251
#ifdef SFL_VIDEO
164
252
    SequenceNode videoCodecs(NULL);
165
253
    accountmap.setKeyValue(VIDEO_CODECS_KEY, &videoCodecs);
166
 
    for (vector<map<string, string> >::iterator i = videoCodecList_.begin(); i != videoCodecList_.end(); ++i) {
167
 
        map<string, string> &codec = *i;
 
254
 
 
255
    for (auto &codec : videoCodecList_) {
168
256
        MappingNode *mapNode = new MappingNode(NULL);
169
257
        mapNode->setKeyValue(VIDEO_CODEC_NAME, new ScalarNode(codec[VIDEO_CODEC_NAME]));
170
258
        mapNode->setKeyValue(VIDEO_CODEC_BITRATE, new ScalarNode(codec[VIDEO_CODEC_BITRATE]));
172
260
        mapNode->setKeyValue(VIDEO_CODEC_PARAMETERS, new ScalarNode(codec[VIDEO_CODEC_PARAMETERS]));
173
261
        videoCodecs.addNode(mapNode);
174
262
    }
 
263
 
175
264
#endif
176
265
 
177
266
    ScalarNode ringtonePath(ringtonePath_);
233
322
    accountmap.setKeyValue(RINGTONE_PATH_KEY, &ringtonePath);
234
323
    accountmap.setKeyValue(RINGTONE_ENABLED_KEY, &ringtoneEnabled);
235
324
    accountmap.setKeyValue(KEEP_ALIVE_ENABLED, &keepAliveEnabled);
 
325
#ifdef SFL_PRESENCE
 
326
    accountmap.setKeyValue(PRESENCE_ENABLED_KEY, &presenceEnabled);
 
327
    accountmap.setKeyValue(PRESENCE_PUBLISH_SUPPORTED_KEY, &presencePublish);
 
328
    accountmap.setKeyValue(PRESENCE_SUBSCRIBE_SUPPORTED_KEY, &presenceSubscribe);
 
329
#endif
236
330
 
237
331
    accountmap.setKeyValue(SRTP_KEY, &srtpmap);
238
332
    srtpmap.setKeyValue(SRTP_ENABLE_KEY, &srtpenabled);
248
342
    SequenceNode credentialseq(NULL);
249
343
    accountmap.setKeyValue(CRED_KEY, &credentialseq);
250
344
 
251
 
    std::vector<std::map<std::string, std::string> >::const_iterator it;
252
 
 
253
 
    for (it = credentials_.begin(); it != credentials_.end(); ++it) {
254
 
        std::map<std::string, std::string> cred = *it;
 
345
    for (const auto &it : credentials_) {
 
346
        std::map<std::string, std::string> cred = it;
255
347
        MappingNode *map = new MappingNode(NULL);
256
348
        map->setKeyValue(CONFIG_ACCOUNT_USERNAME, new ScalarNode(cred[CONFIG_ACCOUNT_USERNAME]));
257
349
        map->setKeyValue(CONFIG_ACCOUNT_PASSWORD, new ScalarNode(cred[CONFIG_ACCOUNT_PASSWORD]));
274
366
    tlsmap.setKeyValue(VERIFY_CLIENT_KEY, &verifyclient);
275
367
    tlsmap.setKeyValue(VERIFY_SERVER_KEY, &verifyserver);
276
368
 
 
369
    ScalarNode userAgent(userAgent_);
 
370
    accountmap.setKeyValue(USER_AGENT_KEY, &userAgent);
 
371
 
 
372
    auto audioPortNodes(serializeRange(accountmap, AUDIO_PORT_MIN_KEY, AUDIO_PORT_MAX_KEY, audioPortRange_));
 
373
#ifdef SFL_VIDEO
 
374
    auto videoPortNodes(serializeRange(accountmap, VIDEO_PORT_MIN_KEY, VIDEO_PORT_MAX_KEY, videoPortRange_));
 
375
#endif
 
376
 
277
377
    try {
278
378
        emitter.serializeAccount(&accountmap);
279
379
    } catch (const YamlEmitterException &e) {
282
382
 
283
383
    // Cleanup
284
384
    Sequence *credSeq = credentialseq.getSequence();
285
 
    for (Sequence::iterator seqit = credSeq->begin(); seqit != credSeq->end(); ++seqit) {
286
 
        MappingNode *node = static_cast<MappingNode*>(*seqit);
 
385
 
 
386
    for (const auto &seqit : *credSeq) {
 
387
        MappingNode *node = static_cast<MappingNode*>(seqit);
287
388
        delete node->getValue(CONFIG_ACCOUNT_USERNAME);
288
389
        delete node->getValue(CONFIG_ACCOUNT_PASSWORD);
289
390
        delete node->getValue(CONFIG_ACCOUNT_REALM);
292
393
 
293
394
#ifdef SFL_VIDEO
294
395
    Sequence *videoCodecSeq = videoCodecs.getSequence();
295
 
    for (Sequence::iterator i = videoCodecSeq->begin(); i != videoCodecSeq->end(); ++i) {
296
 
        MappingNode *node = static_cast<MappingNode*>(*i);
 
396
 
 
397
    for (auto &i : *videoCodecSeq) {
 
398
        MappingNode *node = static_cast<MappingNode*>(i);
297
399
        delete node->getValue(VIDEO_CODEC_NAME);
298
400
        delete node->getValue(VIDEO_CODEC_BITRATE);
299
401
        delete node->getValue(VIDEO_CODEC_ENABLED);
300
402
        delete node->getValue(VIDEO_CODEC_PARAMETERS);
301
403
        delete node;
302
404
    }
 
405
 
303
406
#endif
304
407
}
305
408
 
 
409
void SIPAccount::usePublishedAddressPortInVIA()
 
410
{
 
411
    via_addr_.host.ptr = (char *) publishedIpAddress_.c_str();
 
412
    via_addr_.host.slen = publishedIpAddress_.size();
 
413
    via_addr_.port = publishedPort_;
 
414
}
 
415
 
 
416
namespace {
 
417
template <typename T>
 
418
void validate(std::string &member, const std::string &param,
 
419
              const T& valid)
 
420
{
 
421
    const auto begin = std::begin(valid);
 
422
    const auto end = std::end(valid);
 
423
    if (find(begin, end, param) != end)
 
424
        member = param;
 
425
    else
 
426
        ERROR("Invalid parameter \"%s\"", param.c_str());
 
427
}
 
428
}
 
429
 
306
430
void SIPAccount::unserialize(const Conf::YamlNode &mapNode)
307
431
{
308
432
    using namespace Conf;
312
436
 
313
437
    mapNode.getValue(ALIAS_KEY, &alias_);
314
438
    mapNode.getValue(USERNAME_KEY, &username_);
 
439
 
315
440
    if (not isIP2IP()) mapNode.getValue(HOSTNAME_KEY, &hostname_);
 
441
 
316
442
    mapNode.getValue(ACCOUNT_ENABLE_KEY, &enabled_);
317
443
    mapNode.getValue(ACCOUNT_AUTOANSWER_KEY, &autoAnswerEnabled_);
 
444
 
318
445
    if (not isIP2IP()) mapNode.getValue(MAILBOX_KEY, &mailBox_);
 
446
 
319
447
    mapNode.getValue(AUDIO_CODECS_KEY, &audioCodecStr_);
320
448
    // Update codec list which one is used for SDP offer
321
449
    setActiveAudioCodecs(split_string(audioCodecStr_));
325
453
    if (videoCodecsNode and videoCodecsNode->getType() == SEQUENCE) {
326
454
        SequenceNode *videoCodecs = static_cast<SequenceNode *>(videoCodecsNode);
327
455
        Sequence *seq = videoCodecs->getSequence();
 
456
 
328
457
        if (seq->empty()) {
329
458
            // Video codecs are an empty list
330
459
            WARN("Loading default video codecs");
331
460
            videoCodecList_ = libav_utils::getDefaultCodecs();
332
461
        } else {
333
462
            vector<map<string, string> > videoCodecDetails;
334
 
            for (Sequence::iterator it = seq->begin(); it != seq->end(); ++it) {
335
 
                MappingNode *codec = static_cast<MappingNode *>(*it);
 
463
 
 
464
            for (const auto &it : *seq) {
 
465
                MappingNode *codec = static_cast<MappingNode *>(it);
336
466
                map<string, string> codecMap;
337
467
                codec->getValue(VIDEO_CODEC_NAME, &codecMap[VIDEO_CODEC_NAME]);
338
468
                codec->getValue(VIDEO_CODEC_BITRATE, &codecMap[VIDEO_CODEC_BITRATE]);
340
470
                codec->getValue(VIDEO_CODEC_PARAMETERS, &codecMap[VIDEO_CODEC_PARAMETERS]);
341
471
                videoCodecDetails.push_back(codecMap);
342
472
            }
 
473
 
343
474
            // these must be validated
344
475
            setVideoCodecs(videoCodecDetails);
345
476
        }
349
480
        WARN("Loading default video codecs");
350
481
        videoCodecList_ = libav_utils::getDefaultCodecs();
351
482
    }
 
483
 
352
484
#endif
353
485
 
354
486
    mapNode.getValue(RINGTONE_PATH_KEY, &ringtonePath_);
355
487
    mapNode.getValue(RINGTONE_ENABLED_KEY, &ringtoneEnabled_);
 
488
 
356
489
    if (not isIP2IP()) mapNode.getValue(Preferences::REGISTRATION_EXPIRE_KEY, &registrationExpire_);
 
490
 
357
491
    mapNode.getValue(INTERFACE_KEY, &interface_);
358
492
    int port = DEFAULT_SIP_PORT;
359
493
    mapNode.getValue(PORT_KEY, &port);
362
496
    mapNode.getValue(PUBLISH_PORT_KEY, &port);
363
497
    publishedPort_ = port;
364
498
    mapNode.getValue(SAME_AS_LOCAL_KEY, &publishedSameasLocal_);
 
499
 
 
500
    if (not publishedSameasLocal_)
 
501
        usePublishedAddressPortInVIA();
 
502
 
365
503
    if (not isIP2IP()) mapNode.getValue(KEEP_ALIVE_ENABLED, &keepAliveEnabled_);
366
504
 
 
505
#ifdef SFL_PRESENCE
 
506
    std::string pres;
 
507
    mapNode.getValue(PRESENCE_ENABLED_KEY, &pres);
 
508
    enablePresence(pres == Conf::TRUE_STR);
 
509
    mapNode.getValue(PRESENCE_PUBLISH_SUPPORTED_KEY, &pres);
 
510
    if (presence_)
 
511
        presence_->support(PRESENCE_FUNCTION_PUBLISH, pres == Conf::TRUE_STR);
 
512
    mapNode.getValue(PRESENCE_SUBSCRIBE_SUPPORTED_KEY, &pres);
 
513
    if (presence_)
 
514
        presence_->support(PRESENCE_FUNCTION_SUBSCRIBE, pres == Conf::TRUE_STR);
 
515
#endif
 
516
 
367
517
    std::string dtmfType;
368
518
    mapNode.getValue(DTMF_TYPE_KEY, &dtmfType);
369
519
    dtmfType_ = dtmfType;
372
522
 
373
523
    // stun enabled
374
524
    if (not isIP2IP()) mapNode.getValue(STUN_ENABLED_KEY, &stunEnabled_);
 
525
 
375
526
    if (not isIP2IP()) mapNode.getValue(STUN_SERVER_KEY, &stunServer_);
376
527
 
377
528
    // Init stun server name with default server name
389
540
     */
390
541
    if (credNode && credNode->getType() == SEQUENCE) {
391
542
        SequenceNode *credSeq = static_cast<SequenceNode *>(credNode);
392
 
        Sequence::iterator it;
393
543
        Sequence *seq = credSeq->getSequence();
394
544
 
395
 
        for (it = seq->begin(); it != seq->end(); ++it) {
396
 
            MappingNode *cred = static_cast<MappingNode *>(*it);
 
545
        for (const auto &it : *seq) {
 
546
            MappingNode *cred = static_cast<MappingNode *>(it);
397
547
            std::string user;
398
548
            std::string pass;
399
549
            std::string realm;
412
562
        // migration from old file format
413
563
        std::map<std::string, std::string> credmap;
414
564
        std::string password;
 
565
 
415
566
        if (not isIP2IP()) mapNode.getValue(PASSWORD_KEY, &password);
416
567
 
417
568
        credmap[CONFIG_ACCOUNT_USERNAME] = username_;
427
578
 
428
579
    if (srtpMap) {
429
580
        srtpMap->getValue(SRTP_ENABLE_KEY, &srtpEnabled_);
430
 
        srtpMap->getValue(KEY_EXCHANGE_KEY, &srtpKeyExchange_);
 
581
        std::string tmp;
 
582
        srtpMap->getValue(KEY_EXCHANGE_KEY, &tmp);
 
583
        validate(srtpKeyExchange_, tmp, VALID_SRTP_KEY_EXCHANGES);
431
584
        srtpMap->getValue(RTP_FALLBACK_KEY, &srtpFallback_);
432
585
    }
433
586
 
452
605
        tlsMap->getValue(CERTIFICATE_KEY, &tlsCertificateFile_);
453
606
        tlsMap->getValue(CALIST_KEY, &tlsCaListFile_);
454
607
        tlsMap->getValue(CIPHERS_KEY, &tlsCiphers_);
455
 
        tlsMap->getValue(METHOD_KEY, &tlsMethod_);
 
608
 
 
609
        std::string tmp(tlsMethod_);
 
610
        tlsMap->getValue(METHOD_KEY, &tmp);
 
611
        validate(tlsMethod_, tmp, VALID_TLS_METHODS);
 
612
 
456
613
        tlsMap->getValue(TLS_PASSWORD_KEY, &tlsPassword_);
457
614
        tlsMap->getValue(PRIVATE_KEY_KEY, &tlsPrivateKeyFile_);
458
615
        tlsMap->getValue(REQUIRE_CERTIF_KEY, &tlsRequireClientCertificate_);
463
620
        tlsMap->getValue(TIMEOUT_KEY, &tlsNegotiationTimeoutSec_);
464
621
        tlsMap->getValue(TIMEOUT_KEY, &tlsNegotiationTimeoutMsec_);
465
622
    }
466
 
}
467
 
 
468
 
void SIPAccount::setAccountDetails(std::map<std::string, std::string> details)
 
623
    mapNode.getValue(USER_AGENT_KEY, &userAgent_);
 
624
 
 
625
    unserializeRange(mapNode, AUDIO_PORT_MIN_KEY, AUDIO_PORT_MAX_KEY, audioPortRange_);
 
626
#ifdef SFL_VIDEO
 
627
    unserializeRange(mapNode, VIDEO_PORT_MIN_KEY, VIDEO_PORT_MAX_KEY, videoPortRange_);
 
628
#endif
 
629
}
 
630
 
 
631
namespace {
 
632
 
 
633
template <typename T>
 
634
void parseInt(const std::map<std::string, std::string> &details, const char *key, T &i)
 
635
{
 
636
    const auto iter = details.find(key);
 
637
    if (iter == details.end()) {
 
638
        ERROR("Couldn't find key %s", key);
 
639
        return;
 
640
    }
 
641
    i = atoi(iter->second.c_str());
 
642
}
 
643
 
 
644
}
 
645
 
 
646
void SIPAccount::setAccountDetails(const std::map<std::string, std::string> &details)
469
647
{
470
648
    // Account setting common to SIP and IAX
471
 
    alias_ = details[CONFIG_ACCOUNT_ALIAS];
472
 
    username_ = details[CONFIG_ACCOUNT_USERNAME];
473
 
    hostname_ = details[CONFIG_ACCOUNT_HOSTNAME];
474
 
    enabled_ = details[CONFIG_ACCOUNT_ENABLE] == TRUE_STR;
475
 
    autoAnswerEnabled_ = details[CONFIG_ACCOUNT_AUTOANSWER] == TRUE_STR;
476
 
    ringtonePath_ = details[CONFIG_RINGTONE_PATH];
477
 
    ringtoneEnabled_ = details[CONFIG_RINGTONE_ENABLED] == TRUE_STR;
478
 
    mailBox_ = details[CONFIG_ACCOUNT_MAILBOX];
 
649
    parseString(details, CONFIG_ACCOUNT_ALIAS, alias_);
 
650
    parseString(details, CONFIG_ACCOUNT_USERNAME, username_);
 
651
    parseString(details, CONFIG_ACCOUNT_HOSTNAME, hostname_);
 
652
    parseBool(details, CONFIG_ACCOUNT_ENABLE, enabled_);
 
653
    parseBool(details, CONFIG_ACCOUNT_AUTOANSWER, autoAnswerEnabled_);
 
654
    parseString(details, CONFIG_RINGTONE_PATH, ringtonePath_);
 
655
    parseBool(details, CONFIG_RINGTONE_ENABLED, ringtoneEnabled_);
 
656
    parseString(details, CONFIG_ACCOUNT_MAILBOX, mailBox_);
479
657
 
480
658
    // SIP specific account settings
481
659
 
482
660
    // general sip settings
483
 
    displayName_ = details[CONFIG_DISPLAY_NAME];
484
 
    serviceRoute_ = details[CONFIG_ACCOUNT_ROUTESET];
485
 
    interface_ = details[CONFIG_LOCAL_INTERFACE];
486
 
    publishedSameasLocal_ = details[CONFIG_PUBLISHED_SAMEAS_LOCAL] == TRUE_STR;
487
 
    publishedIpAddress_ = details[CONFIG_PUBLISHED_ADDRESS];
488
 
    localPort_ = atoi(details[CONFIG_LOCAL_PORT].c_str());
489
 
    publishedPort_ = atoi(details[CONFIG_PUBLISHED_PORT].c_str());
490
 
    if (stunServer_ != details[CONFIG_STUN_SERVER]) {
491
 
        link_->sipTransport.destroyStunResolver(stunServer_);
492
 
        // pj_stun_sock_destroy(pj_stun_sock *stun_sock);
493
 
    }
494
 
    stunServer_ = details[CONFIG_STUN_SERVER];
495
 
    stunEnabled_ = details[CONFIG_STUN_ENABLE] == TRUE_STR;
496
 
    dtmfType_ = details[CONFIG_ACCOUNT_DTMF_TYPE];
497
 
    registrationExpire_ = atoi(details[CONFIG_ACCOUNT_REGISTRATION_EXPIRE].c_str());
498
 
    if(registrationExpire_ < MIN_REGISTRATION_TIME)
 
661
    parseString(details, CONFIG_DISPLAY_NAME, displayName_);
 
662
    parseString(details, CONFIG_ACCOUNT_ROUTESET, serviceRoute_);
 
663
    parseString(details, CONFIG_LOCAL_INTERFACE, interface_);
 
664
    parseBool(details, CONFIG_PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal_);
 
665
    parseString(details, CONFIG_PUBLISHED_ADDRESS, publishedIpAddress_);
 
666
    parseInt(details, CONFIG_LOCAL_PORT, localPort_);
 
667
    parseInt(details, CONFIG_PUBLISHED_PORT, publishedPort_);
 
668
 
 
669
    if (not publishedSameasLocal_)
 
670
        usePublishedAddressPortInVIA();
 
671
 
 
672
    parseString(details, CONFIG_STUN_SERVER, stunServer_);
 
673
    parseBool(details, CONFIG_STUN_ENABLE, stunEnabled_);
 
674
    parseString(details, CONFIG_ACCOUNT_DTMF_TYPE, dtmfType_);
 
675
    parseInt(details, CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire_);
 
676
 
 
677
    if (registrationExpire_ < MIN_REGISTRATION_TIME)
499
678
        registrationExpire_ = MIN_REGISTRATION_TIME;
500
679
 
501
 
    userAgent_ = details[CONFIG_ACCOUNT_USERAGENT];
502
 
    keepAliveEnabled_ = details[CONFIG_KEEP_ALIVE_ENABLED] == TRUE_STR;
 
680
    parseString(details, CONFIG_ACCOUNT_USERAGENT, userAgent_);
 
681
    parseBool(details, CONFIG_KEEP_ALIVE_ENABLED, keepAliveEnabled_);
 
682
#ifdef SFL_PRESENCE
 
683
    bool presenceEnabled = false;
 
684
    parseBool(details, CONFIG_PRESENCE_ENABLED, presenceEnabled);
 
685
    enablePresence(presenceEnabled);
 
686
#endif
 
687
 
 
688
    int tmpMin = -1;
 
689
    parseInt(details, CONFIG_ACCOUNT_AUDIO_PORT_MIN, tmpMin);
 
690
    int tmpMax = -1;
 
691
    parseInt(details, CONFIG_ACCOUNT_AUDIO_PORT_MAX, tmpMax);
 
692
    updateRange(tmpMin, tmpMax, audioPortRange_);
 
693
#ifdef SFL_VIDEO
 
694
    tmpMin = -1;
 
695
    parseInt(details, CONFIG_ACCOUNT_VIDEO_PORT_MIN, tmpMin);
 
696
    tmpMax = -1;
 
697
    parseInt(details, CONFIG_ACCOUNT_VIDEO_PORT_MAX, tmpMax);
 
698
    updateRange(tmpMin, tmpMax, videoPortRange_);
 
699
#endif
503
700
 
504
701
    // srtp settings
505
 
    srtpEnabled_ = details[CONFIG_SRTP_ENABLE] == TRUE_STR;
506
 
    srtpFallback_ = details[CONFIG_SRTP_RTP_FALLBACK] == TRUE_STR;
507
 
    zrtpDisplaySas_ = details[CONFIG_ZRTP_DISPLAY_SAS] == TRUE_STR;
508
 
    zrtpDisplaySasOnce_ = details[CONFIG_ZRTP_DISPLAY_SAS_ONCE] == TRUE_STR;
509
 
    zrtpNotSuppWarning_ = details[CONFIG_ZRTP_NOT_SUPP_WARNING] == TRUE_STR;
510
 
    zrtpHelloHash_ = details[CONFIG_ZRTP_HELLO_HASH] == TRUE_STR;
511
 
    srtpKeyExchange_ = details[CONFIG_SRTP_KEY_EXCHANGE];
 
702
    parseBool(details, CONFIG_SRTP_ENABLE, srtpEnabled_);
 
703
    parseBool(details, CONFIG_SRTP_RTP_FALLBACK, srtpFallback_);
 
704
    parseBool(details, CONFIG_ZRTP_DISPLAY_SAS, zrtpDisplaySas_);
 
705
    parseBool(details, CONFIG_ZRTP_DISPLAY_SAS_ONCE, zrtpDisplaySasOnce_);
 
706
    parseBool(details, CONFIG_ZRTP_NOT_SUPP_WARNING, zrtpNotSuppWarning_);
 
707
    parseBool(details, CONFIG_ZRTP_HELLO_HASH, zrtpHelloHash_);
 
708
    auto iter = details.find(CONFIG_SRTP_KEY_EXCHANGE);
 
709
    if (iter != details.end())
 
710
        validate(srtpKeyExchange_, iter->second, VALID_SRTP_KEY_EXCHANGES);
512
711
 
513
712
    // TLS settings
514
 
    tlsListenerPort_ = atoi(details[CONFIG_TLS_LISTENER_PORT].c_str());
515
 
    tlsEnable_ = details[CONFIG_TLS_ENABLE];
516
 
    tlsCaListFile_ = details[CONFIG_TLS_CA_LIST_FILE];
517
 
    tlsCertificateFile_ = details[CONFIG_TLS_CERTIFICATE_FILE];
518
 
    tlsPrivateKeyFile_ = details[CONFIG_TLS_PRIVATE_KEY_FILE];
519
 
    tlsPassword_ = details[CONFIG_TLS_PASSWORD];
520
 
    tlsMethod_ = details[CONFIG_TLS_METHOD];
521
 
    tlsCiphers_ = details[CONFIG_TLS_CIPHERS];
522
 
    tlsServerName_ = details[CONFIG_TLS_SERVER_NAME];
523
 
    tlsVerifyServer_ = details[CONFIG_TLS_VERIFY_SERVER] == TRUE_STR;
524
 
    tlsVerifyClient_ = details[CONFIG_TLS_VERIFY_CLIENT] == TRUE_STR;
525
 
    tlsRequireClientCertificate_ = details[CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE] == TRUE_STR;
526
 
    tlsNegotiationTimeoutSec_ = details[CONFIG_TLS_NEGOTIATION_TIMEOUT_SEC];
527
 
    tlsNegotiationTimeoutMsec_ = details[CONFIG_TLS_NEGOTIATION_TIMEOUT_MSEC];
 
713
    parseBool(details, CONFIG_TLS_ENABLE, tlsEnable_);
 
714
    parseInt(details, CONFIG_TLS_LISTENER_PORT, tlsListenerPort_);
 
715
    parseString(details, CONFIG_TLS_CA_LIST_FILE, tlsCaListFile_);
 
716
    parseString(details, CONFIG_TLS_CERTIFICATE_FILE, tlsCertificateFile_);
 
717
    parseString(details, CONFIG_TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile_);
 
718
    parseString(details, CONFIG_TLS_PASSWORD, tlsPassword_);
 
719
    iter = details.find(CONFIG_TLS_METHOD);
 
720
    if (iter != details.end())
 
721
        validate(tlsMethod_, iter->second, VALID_TLS_METHODS);
 
722
    parseString(details, CONFIG_TLS_CIPHERS, tlsCiphers_);
 
723
    parseString(details, CONFIG_TLS_SERVER_NAME, tlsServerName_);
 
724
    parseBool(details, CONFIG_TLS_VERIFY_SERVER, tlsVerifyServer_);
 
725
    parseBool(details, CONFIG_TLS_VERIFY_CLIENT, tlsVerifyClient_);
 
726
    parseBool(details, CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate_);
 
727
    parseString(details, CONFIG_TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeoutSec_);
 
728
    parseString(details, CONFIG_TLS_NEGOTIATION_TIMEOUT_MSEC, tlsNegotiationTimeoutMsec_);
528
729
 
529
730
    if (credentials_.empty()) { // credentials not set, construct 1 entry
 
731
        WARN("No credentials set, inferring them...");
530
732
        std::vector<std::map<std::string, std::string> > v;
531
733
        std::map<std::string, std::string> map;
532
734
        map[CONFIG_ACCOUNT_USERNAME] = username_;
533
 
        map[CONFIG_ACCOUNT_PASSWORD] = details[CONFIG_ACCOUNT_PASSWORD];
534
 
        map[CONFIG_ACCOUNT_REALM]    = "*";
 
735
        parseString(details, CONFIG_ACCOUNT_PASSWORD, map[CONFIG_ACCOUNT_PASSWORD]);
 
736
        map[CONFIG_ACCOUNT_REALM] = "*";
535
737
        v.push_back(map);
536
738
        setCredentials(v);
537
739
    }
538
740
}
539
741
 
 
742
static std::string retrievePassword(const std::map<std::string, std::string>& map, const std::string &username)
 
743
{
 
744
    std::map<std::string, std::string>::const_iterator map_iter_username;
 
745
    std::map<std::string, std::string>::const_iterator map_iter_password;
 
746
    map_iter_username = map.find(CONFIG_ACCOUNT_USERNAME);
 
747
 
 
748
    if (map_iter_username != map.end()) {
 
749
        if (map_iter_username->second == username) {
 
750
            map_iter_password = map.find(CONFIG_ACCOUNT_PASSWORD);
 
751
 
 
752
            if (map_iter_password != map.end()) {
 
753
                return map_iter_password->second;
 
754
            }
 
755
        }
 
756
    }
 
757
 
 
758
    return "";
 
759
}
 
760
 
 
761
void
 
762
addRangeToDetails(std::map<std::string, std::string> &a, const char *minKey, const char *maxKey, const std::pair<uint16_t, uint16_t> &range)
 
763
{
 
764
    std::ostringstream os;
 
765
    os << range.first;
 
766
    a[minKey] = os.str();
 
767
    os.str("");
 
768
    os << range.second;
 
769
    a[maxKey] = os.str();
 
770
}
 
771
 
540
772
std::map<std::string, std::string> SIPAccount::getAccountDetails() const
541
773
{
542
774
    std::map<std::string, std::string> a;
543
775
 
544
 
    a[CONFIG_ACCOUNT_ID] = accountID_;
545
776
    // note: The IP2IP profile will always have IP2IP as an alias
546
777
    a[CONFIG_ACCOUNT_ALIAS] = alias_;
547
778
 
548
 
    a[CONFIG_ACCOUNT_ENABLE] = enabled_ ? TRUE_STR : FALSE_STR;
549
 
    a[CONFIG_ACCOUNT_AUTOANSWER]= autoAnswerEnabled_ ? TRUE_STR : FALSE_STR;
 
779
    a[CONFIG_ACCOUNT_ENABLE] = enabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
780
    a[CONFIG_ACCOUNT_AUTOANSWER] = autoAnswerEnabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
550
781
    a[CONFIG_ACCOUNT_TYPE] = ACCOUNT_TYPE;
551
782
    a[CONFIG_ACCOUNT_HOSTNAME] = hostname_;
552
783
    a[CONFIG_ACCOUNT_USERNAME] = username_;
 
784
    // get password for this username
 
785
    a[CONFIG_ACCOUNT_PASSWORD] = "";
 
786
 
 
787
    if (hasCredentials()) {
 
788
 
 
789
        for (const auto &vect_item : credentials_) {
 
790
            const std::string password = retrievePassword(vect_item, username_);
 
791
 
 
792
            if (not password.empty())
 
793
                a[CONFIG_ACCOUNT_PASSWORD] = password;
 
794
        }
 
795
    }
553
796
 
554
797
    a[CONFIG_RINGTONE_PATH] = ringtonePath_;
555
 
    a[CONFIG_RINGTONE_ENABLED] = ringtoneEnabled_ ? TRUE_STR : FALSE_STR;
 
798
    a[CONFIG_RINGTONE_ENABLED] = ringtoneEnabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
556
799
    a[CONFIG_ACCOUNT_MAILBOX] = mailBox_;
 
800
#ifdef SFL_PRESENCE
 
801
    a[CONFIG_PRESENCE_ENABLED] = presence_ and presence_->isEnabled()? Conf::TRUE_STR : Conf::FALSE_STR;
 
802
    a[CONFIG_PRESENCE_PUBLISH_SUPPORTED] = presence_ and presence_->isSupported(PRESENCE_FUNCTION_PUBLISH)? Conf::TRUE_STR : Conf::FALSE_STR;
 
803
    a[CONFIG_PRESENCE_SUBSCRIBE_SUPPORTED] = presence_ and presence_->isSupported(PRESENCE_FUNCTION_SUBSCRIBE)? Conf::TRUE_STR : Conf::FALSE_STR;
 
804
    // initialize status values
 
805
    a[CONFIG_PRESENCE_STATUS] = presence_ and presence_->isOnline()? Conf::TRUE_STR : Conf::FALSE_STR;
 
806
    a[CONFIG_PRESENCE_NOTE] = presence_? presence_->getNote() : " ";
 
807
#endif
557
808
 
558
809
    RegistrationState state = UNREGISTERED;
559
810
    std::string registrationStateCode;
570
821
        registrationStateDescription = registrationStateDetailed_.second;
571
822
    }
572
823
 
573
 
    a[CONFIG_ACCOUNT_REGISTRATION_STATUS] = isIP2IP() ? "READY": mapStateNumberToString(state);
 
824
    a[CONFIG_ACCOUNT_REGISTRATION_STATUS] = isIP2IP() ? "READY" : mapStateNumberToString(state);
574
825
    a[CONFIG_ACCOUNT_REGISTRATION_STATE_CODE] = registrationStateCode;
575
826
    a[CONFIG_ACCOUNT_REGISTRATION_STATE_DESC] = registrationStateDescription;
576
827
 
578
829
    a[CONFIG_ACCOUNT_ROUTESET] = serviceRoute_;
579
830
    a[CONFIG_ACCOUNT_USERAGENT] = userAgent_;
580
831
 
 
832
    addRangeToDetails(a, CONFIG_ACCOUNT_AUDIO_PORT_MIN, CONFIG_ACCOUNT_AUDIO_PORT_MAX, audioPortRange_);
 
833
#ifdef SFL_VIDEO
 
834
    addRangeToDetails(a, CONFIG_ACCOUNT_VIDEO_PORT_MIN, CONFIG_ACCOUNT_VIDEO_PORT_MAX, videoPortRange_);
 
835
#endif
 
836
 
581
837
    std::stringstream registrationExpireStr;
582
838
    registrationExpireStr << registrationExpire_;
583
839
    a[CONFIG_ACCOUNT_REGISTRATION_EXPIRE] = registrationExpireStr.str();
584
840
    a[CONFIG_LOCAL_INTERFACE] = interface_;
585
 
    a[CONFIG_PUBLISHED_SAMEAS_LOCAL] = publishedSameasLocal_ ? TRUE_STR : FALSE_STR;
 
841
    a[CONFIG_PUBLISHED_SAMEAS_LOCAL] = publishedSameasLocal_ ? Conf::TRUE_STR : Conf::FALSE_STR;
586
842
    a[CONFIG_PUBLISHED_ADDRESS] = publishedIpAddress_;
587
843
 
588
844
    std::stringstream localport;
591
847
    std::stringstream publishedport;
592
848
    publishedport << publishedPort_;
593
849
    a[CONFIG_PUBLISHED_PORT] = publishedport.str();
594
 
    a[CONFIG_STUN_ENABLE] = stunEnabled_ ? TRUE_STR : FALSE_STR;
 
850
    a[CONFIG_STUN_ENABLE] = stunEnabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
595
851
    a[CONFIG_STUN_SERVER] = stunServer_;
596
852
    a[CONFIG_ACCOUNT_DTMF_TYPE] = dtmfType_;
597
 
    a[CONFIG_KEEP_ALIVE_ENABLED] = keepAliveEnabled_ ? TRUE_STR : FALSE_STR;
 
853
    a[CONFIG_KEEP_ALIVE_ENABLED] = keepAliveEnabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
598
854
 
599
855
    a[CONFIG_SRTP_KEY_EXCHANGE] = srtpKeyExchange_;
600
 
    a[CONFIG_SRTP_ENABLE] = srtpEnabled_ ? TRUE_STR : FALSE_STR;
601
 
    a[CONFIG_SRTP_RTP_FALLBACK] = srtpFallback_ ? TRUE_STR : FALSE_STR;
 
856
    a[CONFIG_SRTP_ENABLE] = srtpEnabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
857
    a[CONFIG_SRTP_RTP_FALLBACK] = srtpFallback_ ? Conf::TRUE_STR : Conf::FALSE_STR;
602
858
 
603
 
    a[CONFIG_ZRTP_DISPLAY_SAS] = zrtpDisplaySas_ ? TRUE_STR : FALSE_STR;
604
 
    a[CONFIG_ZRTP_DISPLAY_SAS_ONCE] = zrtpDisplaySasOnce_ ? TRUE_STR : FALSE_STR;
605
 
    a[CONFIG_ZRTP_HELLO_HASH] = zrtpHelloHash_ ? TRUE_STR : FALSE_STR;
606
 
    a[CONFIG_ZRTP_NOT_SUPP_WARNING] = zrtpNotSuppWarning_ ? TRUE_STR : FALSE_STR;
 
859
    a[CONFIG_ZRTP_DISPLAY_SAS] = zrtpDisplaySas_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
860
    a[CONFIG_ZRTP_DISPLAY_SAS_ONCE] = zrtpDisplaySasOnce_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
861
    a[CONFIG_ZRTP_HELLO_HASH] = zrtpHelloHash_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
862
    a[CONFIG_ZRTP_NOT_SUPP_WARNING] = zrtpNotSuppWarning_ ? Conf::TRUE_STR : Conf::FALSE_STR;
607
863
 
608
864
    // TLS listener is unique and parameters are modified through IP2IP_PROFILE
609
865
    std::stringstream tlslistenerport;
610
866
    tlslistenerport << tlsListenerPort_;
611
867
    a[CONFIG_TLS_LISTENER_PORT] = tlslistenerport.str();
612
 
    a[CONFIG_TLS_ENABLE] = tlsEnable_;
 
868
    a[CONFIG_TLS_ENABLE] = tlsEnable_ ? Conf::TRUE_STR : Conf::FALSE_STR;
613
869
    a[CONFIG_TLS_CA_LIST_FILE] = tlsCaListFile_;
614
870
    a[CONFIG_TLS_CERTIFICATE_FILE] = tlsCertificateFile_;
615
871
    a[CONFIG_TLS_PRIVATE_KEY_FILE] = tlsPrivateKeyFile_;
617
873
    a[CONFIG_TLS_METHOD] = tlsMethod_;
618
874
    a[CONFIG_TLS_CIPHERS] = tlsCiphers_;
619
875
    a[CONFIG_TLS_SERVER_NAME] = tlsServerName_;
620
 
    a[CONFIG_TLS_VERIFY_SERVER] = tlsVerifyServer_ ? TRUE_STR : FALSE_STR;
621
 
    a[CONFIG_TLS_VERIFY_CLIENT] = tlsVerifyClient_ ? TRUE_STR : FALSE_STR;
622
 
    a[CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE] = tlsRequireClientCertificate_ ? TRUE_STR : FALSE_STR;
 
876
    a[CONFIG_TLS_VERIFY_SERVER] = tlsVerifyServer_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
877
    a[CONFIG_TLS_VERIFY_CLIENT] = tlsVerifyClient_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
878
    a[CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE] = tlsRequireClientCertificate_ ? Conf::TRUE_STR : Conf::FALSE_STR;
623
879
    a[CONFIG_TLS_NEGOTIATION_TIMEOUT_SEC] = tlsNegotiationTimeoutSec_;
624
880
    a[CONFIG_TLS_NEGOTIATION_TIMEOUT_MSEC] = tlsNegotiationTimeoutMsec_;
625
881
 
631
887
    if (hostname_.length() >= PJ_MAX_HOSTNAME)
632
888
        return;
633
889
 
 
890
#if HAVE_TLS
 
891
 
634
892
    // Init TLS settings if the user wants to use TLS
635
 
    if (tlsEnable_ == TRUE_STR) {
 
893
    if (tlsEnable_) {
636
894
        DEBUG("TLS is enabled for account %s", accountID_.c_str());
637
895
        transportType_ = PJSIP_TRANSPORT_TLS;
638
896
        initTlsConfiguration();
639
897
    }
640
898
 
 
899
#endif
 
900
 
641
901
    // Init STUN settings for this account if the user selected it
642
902
    if (stunEnabled_) {
643
903
        transportType_ = PJSIP_TRANSPORT_START_OTHER;
656
916
    } catch (const VoipLinkException &e) {
657
917
        ERROR("%s", e.what());
658
918
    }
 
919
 
 
920
#ifdef SFL_PRESENCE
 
921
    getPresence()->subscribeClient(getFromUri(), true); //self presence subscription
 
922
    getPresence()->sendPresence(true,""); // try to publish whatever the status is.
 
923
#endif
659
924
}
660
925
 
661
926
void SIPAccount::unregisterVoIPLink()
670
935
    }
671
936
}
672
937
 
673
 
void SIPAccount::startKeepAliveTimer() {
 
938
void SIPAccount::startKeepAliveTimer()
 
939
{
674
940
 
675
941
    if (isTlsEnabled())
676
942
        return;
716
982
    }
717
983
}
718
984
 
 
985
#if HAVE_TLS
719
986
pjsip_ssl_method SIPAccount::sslMethodStringToPjEnum(const std::string& method)
720
987
{
721
988
    if (method == "Default")
733
1000
    return PJSIP_SSL_UNSPECIFIED_METHOD;
734
1001
}
735
1002
 
736
 
void SIPAccount::displayCipherSuite()
 
1003
void SIPAccount::trimCiphers()
737
1004
{
738
 
    CipherArray::const_iterator iter;
739
 
    for (iter = ciphers.begin(); iter != ciphers.end(); ++iter)
740
 
        DEBUG("Cipher: %s", pj_ssl_cipher_name(*iter));
 
1005
    int sum = 0;
 
1006
    int count = 0;
 
1007
 
 
1008
    // PJSIP aborts if our cipher list exceeds 1000 characters
 
1009
    static const int MAX_CIPHERS_STRLEN = 1000;
 
1010
 
 
1011
    for (const auto &item : ciphers_) {
 
1012
        sum += strlen(pj_ssl_cipher_name(item));
 
1013
 
 
1014
        if (sum > MAX_CIPHERS_STRLEN)
 
1015
            break;
 
1016
 
 
1017
        ++count;
 
1018
    }
 
1019
 
 
1020
    ciphers_.resize(count);
 
1021
    DEBUG("Using %u ciphers", ciphers_.size());
741
1022
}
742
1023
 
743
1024
void SIPAccount::initTlsConfiguration()
744
1025
{
745
 
    pj_status_t status;
746
1026
    unsigned cipherNum;
747
1027
 
748
1028
    // Determine the cipher list supported on this machine
749
 
    cipherNum = ciphers.size();
750
 
    status = pj_ssl_cipher_get_availables(&ciphers.front(), &cipherNum);
751
 
    if (status != PJ_SUCCESS) {
 
1029
    cipherNum = ciphers_.size();
 
1030
 
 
1031
    if (pj_ssl_cipher_get_availables(&ciphers_.front(), &cipherNum) != PJ_SUCCESS)
752
1032
        ERROR("Could not determine cipher list on this system");
753
 
    }
754
 
 
755
 
    ciphers.resize(cipherNum);
 
1033
 
 
1034
    ciphers_.resize(cipherNum);
 
1035
 
 
1036
    trimCiphers();
756
1037
 
757
1038
    // TLS listener is unique and should be only modified through IP2IP_PROFILE
758
1039
    pjsip_tls_setting_default(&tlsSetting_);
762
1043
    pj_cstr(&tlsSetting_.privkey_file, tlsPrivateKeyFile_.c_str());
763
1044
    pj_cstr(&tlsSetting_.password, tlsPassword_.c_str());
764
1045
    tlsSetting_.method = sslMethodStringToPjEnum(tlsMethod_);
765
 
    tlsSetting_.ciphers_num = ciphers.size();
766
 
    tlsSetting_.ciphers = &ciphers.front();
 
1046
    tlsSetting_.ciphers_num = ciphers_.size();
 
1047
    tlsSetting_.ciphers = &ciphers_.front();
767
1048
 
768
 
    tlsSetting_.verify_server = tlsVerifyServer_ ? PJ_TRUE: PJ_FALSE;
769
 
    tlsSetting_.verify_client = tlsVerifyClient_ ? PJ_TRUE: PJ_FALSE;
770
 
    tlsSetting_.require_client_cert = tlsRequireClientCertificate_ ? PJ_TRUE: PJ_FALSE;
 
1049
    tlsSetting_.verify_server = tlsVerifyServer_;
 
1050
    tlsSetting_.verify_client = tlsVerifyClient_;
 
1051
    tlsSetting_.require_client_cert = tlsRequireClientCertificate_;
771
1052
 
772
1053
    tlsSetting_.timeout.sec = atol(tlsNegotiationTimeoutSec_.c_str());
773
1054
    tlsSetting_.timeout.msec = atol(tlsNegotiationTimeoutMsec_.c_str());
776
1057
    tlsSetting_.qos_ignore_error = PJ_TRUE;
777
1058
}
778
1059
 
 
1060
#endif
 
1061
 
779
1062
void SIPAccount::initStunConfiguration()
780
1063
{
781
1064
    size_t pos;
803
1086
    if (registrationExpire_ == 0)
804
1087
        registrationExpire_ = DEFAULT_REGISTRATION_TIME; /** Default expire value for registration */
805
1088
 
806
 
    if (tlsEnable_ == TRUE_STR) {
 
1089
#if HAVE_TLS
 
1090
 
 
1091
    if (tlsEnable_) {
807
1092
        initTlsConfiguration();
808
1093
        transportType_ = PJSIP_TRANSPORT_TLS;
809
1094
    } else
 
1095
#endif
810
1096
        transportType_ = PJSIP_TRANSPORT_UDP;
811
1097
}
812
1098
 
821
1107
}
822
1108
 
823
1109
namespace {
824
 
    bool haveValueInCommon(const std::vector<std::string> &a, const std::vector<std::string> &b)
825
 
    {
826
 
        for (std::vector<std::string>::const_iterator i = a.begin(); i != a.end(); ++i)
827
 
            if (std::find(b.begin(), b.end(), *i) != b.end())
828
 
                return true;
829
 
        return false;
830
 
    }
 
1110
bool haveValueInCommon(const std::vector<std::string> &a, const std::vector<std::string> &b)
 
1111
{
 
1112
    for (const auto &i : a)
 
1113
        if (std::find(b.begin(), b.end(), i) != b.end())
 
1114
            return true;
 
1115
 
 
1116
    return false;
 
1117
}
831
1118
}
832
1119
 
833
1120
bool SIPAccount::hostnameMatch(const std::string& hostname, pjsip_endpoint * /*endpt*/, pj_pool_t * /*pool*/) const
834
1121
{
835
1122
    if (hostname == hostname_)
836
1123
        return true;
 
1124
 
837
1125
    const std::vector<std::string> a(sip_utils::getIPList(hostname));
838
1126
    const std::vector<std::string> b(sip_utils::getIPList(hostname_));
839
1127
    return haveValueInCommon(a, b);
843
1131
{
844
1132
    if (hostname == serviceRoute_)
845
1133
        return true;
 
1134
 
846
1135
    const std::vector<std::string> a(sip_utils::getIPList(hostname));
847
1136
    const std::vector<std::string> b(sip_utils::getIPList(serviceRoute_));
848
1137
    return haveValueInCommon(a, b);
921
1210
}
922
1211
 
923
1212
 
924
 
std::string SIPAccount::getContactHeader() const
 
1213
pj_str_t
 
1214
SIPAccount::getContactHeader()
925
1215
{
926
1216
    if (transport_ == NULL)
927
1217
        ERROR("Transport not created yet");
928
1218
 
929
1219
    // The transport type must be specified, in our case START_OTHER refers to stun transport
930
1220
    pjsip_transport_type_e transportType = transportType_;
 
1221
 
931
1222
    if (transportType == PJSIP_TRANSPORT_START_OTHER)
932
1223
        transportType = PJSIP_TRANSPORT_UDP;
933
1224
 
935
1226
    std::string address, port;
936
1227
    std::ostringstream portstr;
937
1228
 
938
 
    link_->sipTransport.findLocalAddressFromTransport(transport_, transportType, address, port);
939
 
 
940
 
    if (!receivedParameter_.empty())
941
 
       address = receivedParameter_;
942
 
 
943
 
    if (rPort_ != -1) {
944
 
        portstr << rPort_;
 
1229
    link_->sipTransport->findLocalAddressFromTransport(transport_, transportType, address, port);
 
1230
 
 
1231
    if (not publishedSameasLocal_) {
 
1232
        address = publishedIpAddress_;
 
1233
        portstr << publishedPort_;
945
1234
        port = portstr.str();
 
1235
        DEBUG("Using published address %s and port %s", address.c_str(), port.c_str());
 
1236
    } else if (stunEnabled_) {
 
1237
        link_->sipTransport->findLocalAddressFromSTUN(transport_, &stunServerName_, stunPort_, address, port);
 
1238
        publishedIpAddress_ = address;
 
1239
        publishedPort_ = atoi(port.c_str());
 
1240
        usePublishedAddressPortInVIA();
 
1241
    } else {
 
1242
        if (!receivedParameter_.empty()) {
 
1243
            address = receivedParameter_;
 
1244
            DEBUG("Using received address %s", address.c_str());
 
1245
        }
 
1246
 
 
1247
        if (rPort_ != -1 and rPort_ != 0) {
 
1248
            portstr << rPort_;
 
1249
            port = portstr.str();
 
1250
            DEBUG("Using received port %s", port.c_str());
 
1251
        }
946
1252
    }
947
1253
 
948
1254
    // UDP does not require the transport specification
949
1255
    std::string scheme;
950
1256
    std::string transport;
 
1257
 
951
1258
    if (transportType_ == PJSIP_TRANSPORT_TLS) {
952
1259
        scheme = "sips:";
953
1260
        transport = ";transport=" + std::string(pjsip_transport_get_type_name(transportType));
954
1261
    } else
955
1262
        scheme = "sip:";
956
1263
 
957
 
    return displayName_ + (displayName_.empty() ? "" : " ") + "<" +
958
 
           scheme + username_ + (username_.empty() ? "" : "@") +
959
 
           address + ":" + port + transport + ">";
 
1264
    contact_.slen = pj_ansi_snprintf(contact_.ptr, PJSIP_MAX_URL_SIZE,
 
1265
                                     "%s%s<%s%s%s%s:%s%s>",
 
1266
                                     displayName_.c_str(),
 
1267
                                     (displayName_.empty() ? "" : " "),
 
1268
                                     scheme.c_str(),
 
1269
                                     username_.c_str(),
 
1270
                                     (username_.empty() ? "" : "@"),
 
1271
                                     address.c_str(),
 
1272
                                     port.c_str(),
 
1273
                                     transport.c_str());
 
1274
    return contact_;
960
1275
}
961
1276
 
 
1277
pjsip_host_port
 
1278
SIPAccount::getHostPortFromSTUN(pj_pool_t *pool)
 
1279
{
 
1280
    std::string addr, port;
 
1281
    link_->sipTransport->findLocalAddressFromSTUN(transport_, &stunServerName_, stunPort_, addr, port);
 
1282
    pjsip_host_port result;
 
1283
    pj_strdup2(pool, &result.host, addr.c_str());
 
1284
    result.host.slen = addr.length();
 
1285
    std::stringstream ss;
 
1286
    ss << port;
 
1287
    ss >> result.port;
 
1288
    return result;
 
1289
}
962
1290
 
963
1291
void SIPAccount::keepAliveRegistrationCb(UNUSED pj_timer_heap_t *th, pj_timer_entry *te)
964
1292
{
987
1315
 
988
1316
namespace {
989
1317
std::string computeMd5HashFromCredential(const std::string& username,
990
 
                                         const std::string& password,
991
 
                                         const std::string& realm)
 
1318
        const std::string& password,
 
1319
        const std::string& realm)
992
1320
{
993
1321
#define MD5_APPEND(pms,buf,len) pj_md5_update(pms, (const pj_uint8_t*)buf, len)
994
1322
 
1009
1337
    char hash[32];
1010
1338
 
1011
1339
    for (int i = 0; i < 16; ++i)
1012
 
        pj_val_to_hex_digit(digest[i], &hash[2*i]);
 
1340
        pj_val_to_hex_digit(digest[i], &hash[2 * i]);
1013
1341
 
1014
1342
    return std::string(hash, 32);
1015
1343
}
1032
1360
    credentials_ = creds;
1033
1361
 
1034
1362
    /* md5 hashing */
1035
 
    for (vector<map<string, string> >::iterator it = credentials_.begin(); it != credentials_.end(); ++it) {
1036
 
        map<string, string>::const_iterator val = (*it).find(CONFIG_ACCOUNT_USERNAME);
1037
 
        const std::string username = val != (*it).end() ? val->second : "";
1038
 
        val = (*it).find(CONFIG_ACCOUNT_REALM);
1039
 
        const std::string realm(val != (*it).end() ? val->second : "");
1040
 
        val = (*it).find(CONFIG_ACCOUNT_PASSWORD);
1041
 
        const std::string password(val != (*it).end() ? val->second : "");
 
1363
    for (auto &it : credentials_) {
 
1364
        map<string, string>::const_iterator val = it.find(CONFIG_ACCOUNT_USERNAME);
 
1365
        const std::string username = val != it.end() ? val->second : "";
 
1366
        val = it.find(CONFIG_ACCOUNT_REALM);
 
1367
        const std::string realm(val != it.end() ? val->second : "");
 
1368
        val = it.find(CONFIG_ACCOUNT_PASSWORD);
 
1369
        const std::string password(val != it.end() ? val->second : "");
1042
1370
 
1043
1371
        if (md5HashingEnabled) {
1044
1372
            // TODO: Fix this.
1051
1379
            // re-hash a hashed password.
1052
1380
 
1053
1381
            if (password.length() != 32)
1054
 
                (*it)[CONFIG_ACCOUNT_PASSWORD] = computeMd5HashFromCredential(username, password, realm);
 
1382
                it[CONFIG_ACCOUNT_PASSWORD] = computeMd5HashFromCredential(username, password, realm);
1055
1383
        }
1056
1384
    }
1057
1385
 
1059
1387
    cred_.resize(credentials_.size());
1060
1388
 
1061
1389
    size_t i = 0;
1062
 
    for (vector<map<string, string > >::const_iterator iter = credentials_.begin();
1063
 
            iter != credentials_.end(); ++iter) {
1064
 
        map<string, string>::const_iterator val = (*iter).find(CONFIG_ACCOUNT_PASSWORD);
1065
 
        const std::string password = val != (*iter).end() ? val->second : "";
 
1390
 
 
1391
    for (const auto &item : credentials_) {
 
1392
        map<string, string>::const_iterator val = item.find(CONFIG_ACCOUNT_PASSWORD);
 
1393
        const std::string password = val != item.end() ? val->second : "";
1066
1394
        int dataType = (md5HashingEnabled and password.length() == 32)
1067
1395
                       ? PJSIP_CRED_DATA_DIGEST
1068
1396
                       : PJSIP_CRED_DATA_PLAIN_PASSWD;
1069
1397
 
1070
 
        val = (*iter).find(CONFIG_ACCOUNT_USERNAME);
 
1398
        val = item.find(CONFIG_ACCOUNT_USERNAME);
1071
1399
 
1072
 
        if (val != (*iter).end())
 
1400
        if (val != item.end())
1073
1401
            cred_[i].username = pj_str((char*) val->second.c_str());
1074
1402
 
1075
1403
        cred_[i].data = pj_str((char*) password.c_str());
1076
1404
 
1077
 
        val = (*iter).find(CONFIG_ACCOUNT_REALM);
 
1405
        val = item.find(CONFIG_ACCOUNT_REALM);
1078
1406
 
1079
 
        if (val != (*iter).end())
 
1407
        if (val != item.end())
1080
1408
            cred_[i].realm = pj_str((char*) val->second.c_str());
1081
1409
 
1082
1410
        cred_[i].data_type = dataType;
1093
1421
 
1094
1422
std::string SIPAccount::getUserAgentName() const
1095
1423
{
1096
 
    std::string result(userAgent_);
1097
 
 
1098
 
    if (result == "sflphone" or result.empty())
1099
 
        result += "/" PACKAGE_VERSION;
1100
 
 
1101
 
    return result;
 
1424
    return userAgent_.empty() ? DEFAULT_USER_AGENT : userAgent_;
1102
1425
}
1103
1426
 
1104
1427
std::map<std::string, std::string> SIPAccount::getIp2IpDetails() const
1105
1428
{
1106
1429
    assert(isIP2IP());
1107
1430
    std::map<std::string, std::string> ip2ipAccountDetails;
1108
 
    ip2ipAccountDetails[CONFIG_ACCOUNT_ID] = IP2IP_PROFILE;
1109
1431
    ip2ipAccountDetails[CONFIG_SRTP_KEY_EXCHANGE] = srtpKeyExchange_;
1110
 
    ip2ipAccountDetails[CONFIG_SRTP_ENABLE] = srtpEnabled_ ? TRUE_STR : FALSE_STR;
1111
 
    ip2ipAccountDetails[CONFIG_SRTP_RTP_FALLBACK] = srtpFallback_ ? TRUE_STR : FALSE_STR;
1112
 
    ip2ipAccountDetails[CONFIG_ZRTP_DISPLAY_SAS] = zrtpDisplaySas_ ? TRUE_STR : FALSE_STR;
1113
 
    ip2ipAccountDetails[CONFIG_ZRTP_HELLO_HASH] = zrtpHelloHash_ ? TRUE_STR : FALSE_STR;
1114
 
    ip2ipAccountDetails[CONFIG_ZRTP_NOT_SUPP_WARNING] = zrtpNotSuppWarning_ ? TRUE_STR : FALSE_STR;
1115
 
    ip2ipAccountDetails[CONFIG_ZRTP_DISPLAY_SAS_ONCE] = zrtpDisplaySasOnce_ ? TRUE_STR : FALSE_STR;
 
1432
    ip2ipAccountDetails[CONFIG_SRTP_ENABLE] = srtpEnabled_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1433
    ip2ipAccountDetails[CONFIG_SRTP_RTP_FALLBACK] = srtpFallback_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1434
    ip2ipAccountDetails[CONFIG_ZRTP_DISPLAY_SAS] = zrtpDisplaySas_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1435
    ip2ipAccountDetails[CONFIG_ZRTP_HELLO_HASH] = zrtpHelloHash_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1436
    ip2ipAccountDetails[CONFIG_ZRTP_NOT_SUPP_WARNING] = zrtpNotSuppWarning_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1437
    ip2ipAccountDetails[CONFIG_ZRTP_DISPLAY_SAS_ONCE] = zrtpDisplaySasOnce_ ? Conf::TRUE_STR : Conf::FALSE_STR;
1116
1438
    ip2ipAccountDetails[CONFIG_LOCAL_INTERFACE] = interface_;
1117
1439
    std::stringstream portstr;
1118
1440
    portstr << localPort_;
1133
1455
    std::stringstream portstr;
1134
1456
    portstr << tlsListenerPort_;
1135
1457
    tlsSettings[CONFIG_TLS_LISTENER_PORT] = portstr.str();
1136
 
    tlsSettings[CONFIG_TLS_ENABLE] = tlsEnable_;
 
1458
    tlsSettings[CONFIG_TLS_ENABLE] = tlsEnable_ ? Conf::TRUE_STR : Conf::FALSE_STR;
1137
1459
    tlsSettings[CONFIG_TLS_CA_LIST_FILE] = tlsCaListFile_;
1138
1460
    tlsSettings[CONFIG_TLS_CERTIFICATE_FILE] = tlsCertificateFile_;
1139
1461
    tlsSettings[CONFIG_TLS_PRIVATE_KEY_FILE] = tlsPrivateKeyFile_;
1141
1463
    tlsSettings[CONFIG_TLS_METHOD] = tlsMethod_;
1142
1464
    tlsSettings[CONFIG_TLS_CIPHERS] = tlsCiphers_;
1143
1465
    tlsSettings[CONFIG_TLS_SERVER_NAME] = tlsServerName_;
1144
 
    tlsSettings[CONFIG_TLS_VERIFY_SERVER] = tlsVerifyServer_ ? TRUE_STR : FALSE_STR;
1145
 
    tlsSettings[CONFIG_TLS_VERIFY_CLIENT] = tlsVerifyClient_ ? TRUE_STR : FALSE_STR;
1146
 
    tlsSettings[CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE] = tlsRequireClientCertificate_ ? TRUE_STR : FALSE_STR;
 
1466
    tlsSettings[CONFIG_TLS_VERIFY_SERVER] = tlsVerifyServer_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1467
    tlsSettings[CONFIG_TLS_VERIFY_CLIENT] = tlsVerifyClient_ ? Conf::TRUE_STR : Conf::FALSE_STR;
 
1468
    tlsSettings[CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE] = tlsRequireClientCertificate_ ? Conf::TRUE_STR : Conf::FALSE_STR;
1147
1469
    tlsSettings[CONFIG_TLS_NEGOTIATION_TIMEOUT_SEC] = tlsNegotiationTimeoutSec_;
1148
1470
    tlsSettings[CONFIG_TLS_NEGOTIATION_TIMEOUT_MSEC] = tlsNegotiationTimeoutMsec_;
1149
1471
 
1164
1486
    std::map<std::string, std::string>::const_iterator it = details.find(key);
1165
1487
 
1166
1488
    if (it != details.end())
1167
 
        val = it->second == TRUE_STR;
 
1489
        val = it->second == Conf::TRUE_STR;
1168
1490
}
1169
1491
 
1170
1492
void set_opt(const std::map<std::string, std::string> &details, const char *key, pj_uint16_t &val)
1204
1526
    return accountID_ == IP2IP_PROFILE;
1205
1527
}
1206
1528
 
1207
 
bool SIPAccount::matches(const std::string &userName, const std::string &server,
1208
 
                         pjsip_endpoint *endpt, pj_pool_t *pool) const
 
1529
#ifdef SFL_PRESENCE
 
1530
SIPPresence * SIPAccount::getPresence() const
 
1531
{
 
1532
    return presence_;
 
1533
}
 
1534
 
 
1535
/**
 
1536
 *  Enable the presence module
 
1537
 */
 
1538
void
 
1539
SIPAccount::enablePresence(const bool& enabled)
 
1540
{
 
1541
    DEBUG("Presence enable for %s : %s.",
 
1542
            accountID_.c_str(),
 
1543
            enabled? Conf::TRUE_STR : Conf::FALSE_STR);
 
1544
 
 
1545
    if (presence_)
 
1546
        presence_->enable(enabled);
 
1547
}
 
1548
 
 
1549
/**
 
1550
 *  Set the presence (PUBLISH/SUBSCRIBE) support flags
 
1551
 *  and process the change.
 
1552
 */
 
1553
void
 
1554
SIPAccount::supportPresence(int function, bool enabled)
 
1555
{
 
1556
    if (getPresence()->isSupported(function) == enabled)
 
1557
        return;
 
1558
 
 
1559
    DEBUG("Presence support for %s (%s: %s).", accountID_.c_str(),
 
1560
          function == PRESENCE_FUNCTION_PUBLISH ? "publish" : "subscribe",
 
1561
          enabled ? Conf::TRUE_STR : Conf::FALSE_STR);
 
1562
    if (presence_)
 
1563
        presence_->support(function, enabled);
 
1564
 
 
1565
    // force presence to disable when nothing is supported
 
1566
    if (not getPresence()->isSupported(PRESENCE_FUNCTION_PUBLISH) and
 
1567
        not getPresence()->isSupported(PRESENCE_FUNCTION_SUBSCRIBE))
 
1568
        enablePresence(false);
 
1569
 
 
1570
    Manager::instance().saveConfig();
 
1571
    Manager::instance().getClient()->getConfigurationManager()->accountsChanged();
 
1572
}
 
1573
#endif
 
1574
 
 
1575
MatchRank
 
1576
SIPAccount::matches(const std::string &userName, const std::string &server,
 
1577
                    pjsip_endpoint *endpt, pj_pool_t *pool) const
1209
1578
{
1210
1579
    if (fullMatch(userName, server, endpt, pool)) {
1211
1580
        DEBUG("Matching account id in request is a fullmatch %s@%s", userName.c_str(), server.c_str());
1212
 
        return true;
 
1581
        return MatchRank::FULL;
1213
1582
    } else if (hostnameMatch(server, endpt, pool)) {
1214
1583
        DEBUG("Matching account id in request with hostname %s", server.c_str());
1215
 
        return true;
 
1584
        return MatchRank::PARTIAL;
1216
1585
    } else if (userMatch(userName)) {
1217
1586
        DEBUG("Matching account id in request with username %s", userName.c_str());
1218
 
        return true;
 
1587
        return MatchRank::PARTIAL;
1219
1588
    } else if (proxyMatch(server, endpt, pool)) {
1220
1589
        DEBUG("Matching account id in request with proxy %s", server.c_str());
1221
 
        return true;
1222
 
    } else
1223
 
        return false;
 
1590
        return MatchRank::PARTIAL;
 
1591
    } else {
 
1592
        return MatchRank::NONE;
 
1593
    }
 
1594
}
 
1595
 
 
1596
// returns even number in range [lower, upper]
 
1597
uint16_t
 
1598
SIPAccount::getRandomEvenNumber(const std::pair<uint16_t, uint16_t> &range)
 
1599
{
 
1600
    const uint16_t halfUpper = range.second * 0.5;
 
1601
    const uint16_t halfLower = range.first * 0.5;
 
1602
    uint16_t result;
 
1603
    do {
 
1604
        result = 2 * (halfLower + rand() % (halfUpper - halfLower + 1));
 
1605
    } while (portsInUse_[result / 2]);
 
1606
 
 
1607
    portsInUse_[result / 2] = true;
 
1608
    return result;
 
1609
}
 
1610
 
 
1611
void
 
1612
SIPAccount::releasePort(uint16_t port)
 
1613
{
 
1614
    portsInUse_[port / 2] = false;
 
1615
}
 
1616
 
 
1617
uint16_t
 
1618
SIPAccount::generateAudioPort() const
 
1619
{
 
1620
    return getRandomEvenNumber(audioPortRange_);
 
1621
}
 
1622
 
 
1623
#ifdef SFL_VIDEO
 
1624
uint16_t
 
1625
SIPAccount::generateVideoPort() const
 
1626
{
 
1627
    return getRandomEvenNumber(videoPortRange_);
 
1628
}
 
1629
#endif
 
1630
 
 
1631
void
 
1632
SIPAccount::destroyRegistrationInfo()
 
1633
{
 
1634
    pjsip_regc_destroy(regc_);
 
1635
    regc_ = nullptr;
 
1636
}
 
1637
 
 
1638
void
 
1639
SIPAccount::resetAutoRegistration()
 
1640
{
 
1641
    auto_rereg_.active = PJ_FALSE;
 
1642
    auto_rereg_.attempt_cnt = 0;
 
1643
}
 
1644
 
 
1645
/* Check if IP is private IP address */
 
1646
static pj_bool_t
 
1647
is_private_ip(const pj_str_t *addr)
 
1648
{
 
1649
    const pj_str_t private_net[] =
 
1650
    {
 
1651
    { (char*) "10.", 3 },
 
1652
    { (char*) "127.", 4 },
 
1653
    { (char*) "172.16.", 7 },
 
1654
    { (char*) "192.168.", 8 }
 
1655
    };
 
1656
 
 
1657
    for (unsigned i = 0; i < PJ_ARRAY_SIZE(private_net); ++i)
 
1658
        if (pj_strncmp(addr, &private_net[i], private_net[i].slen) == 0)
 
1659
            return PJ_TRUE;
 
1660
 
 
1661
    return PJ_FALSE;
 
1662
}
 
1663
 
 
1664
 
 
1665
/* Update NAT address from the REGISTER response */
 
1666
bool
 
1667
SIPAccount::checkNATAddress(pjsip_regc_cbparam *param, pj_pool_t *pool)
 
1668
{
 
1669
    pjsip_transport *tp = param->rdata->tp_info.transport;
 
1670
 
 
1671
    /* Get the received and rport info */
 
1672
    pjsip_via_hdr *via = param->rdata->msg_info.via;
 
1673
    int rport;
 
1674
    if (via->rport_param < 1) {
 
1675
        /* Remote doesn't support rport */
 
1676
        rport = via->sent_by.port;
 
1677
        if (rport == 0) {
 
1678
            pjsip_transport_type_e tp_type;
 
1679
            tp_type = (pjsip_transport_type_e) tp->key.type;
 
1680
            rport = pjsip_transport_get_default_port_for_type(tp_type);
 
1681
        }
 
1682
    } else {
 
1683
        rport = via->rport_param;
 
1684
    }
 
1685
 
 
1686
    const pj_str_t *via_addr = via->recvd_param.slen != 0 ?
 
1687
        &via->recvd_param : &via->sent_by.host;
 
1688
 
 
1689
    /* If allowViaRewrite_ is enabled, we save the Via "received" address
 
1690
     * from the response.
 
1691
     */
 
1692
    if (allowViaRewrite_ and (via_addr_.host.slen == 0 or via_tp_ != tp)) {
 
1693
        if (pj_strcmp(&via_addr_.host, via_addr))
 
1694
            pj_strdup(pool, &via_addr_.host, via_addr);
 
1695
 
 
1696
        via_addr_.port = rport;
 
1697
        via_tp_ = tp;
 
1698
        pjsip_regc_set_via_sent_by(regc_, &via_addr_, via_tp_);
 
1699
    }
 
1700
 
 
1701
    /* Only update if account is configured to auto-update */
 
1702
    if (not allowContactRewrite_)
 
1703
        return false;
 
1704
 
 
1705
    /* Compare received and rport with the URI in our registration */
 
1706
    const pj_str_t STR_CONTACT = { (char*) "Contact", 7 };
 
1707
    pjsip_contact_hdr *contact_hdr = (pjsip_contact_hdr*)
 
1708
    pjsip_parse_hdr(pool, &STR_CONTACT, contact_.ptr, contact_.slen, NULL);
 
1709
    pj_assert(contact_hdr != NULL);
 
1710
    pjsip_sip_uri *uri = (pjsip_sip_uri*) contact_hdr->uri;
 
1711
    pj_assert(uri != NULL);
 
1712
    uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri);
 
1713
 
 
1714
    if (uri->port == 0) {
 
1715
        pjsip_transport_type_e tp_type;
 
1716
        tp_type = (pjsip_transport_type_e) tp->key.type;
 
1717
        uri->port = pjsip_transport_get_default_port_for_type(tp_type);
 
1718
    }
 
1719
 
 
1720
    /* Convert IP address strings into sockaddr for comparison.
 
1721
     * (http://trac.pjsip.org/repos/ticket/863)
 
1722
     */
 
1723
    pj_sockaddr contact_addr, recv_addr;
 
1724
    pj_status_t status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &uri->host, &contact_addr);
 
1725
    if (status == PJ_SUCCESS)
 
1726
        status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, via_addr, &recv_addr);
 
1727
 
 
1728
    bool matched;
 
1729
    if (status == PJ_SUCCESS) {
 
1730
        // Compare the addresses as sockaddr according to the ticket above
 
1731
        matched = (uri->port == rport and pj_sockaddr_cmp(&contact_addr, &recv_addr) == 0);
 
1732
    } else {
 
1733
        // Compare the addresses as string, as before
 
1734
        matched = (uri->port == rport and pj_stricmp(&uri->host, via_addr) == 0);
 
1735
    }
 
1736
 
 
1737
    if (matched) {
 
1738
        // Address doesn't change
 
1739
        return false;
 
1740
    }
 
1741
 
 
1742
    /* Get server IP */
 
1743
    pj_str_t srv_ip = pj_str(param->rdata->pkt_info.src_name);
 
1744
 
 
1745
    /* At this point we've detected that the address as seen by registrar.
 
1746
     * has changed.
 
1747
     */
 
1748
 
 
1749
    /* Do not switch if both Contact and server's IP address are
 
1750
     * public but response contains private IP. A NAT in the middle
 
1751
     * might have messed up with the SIP packets. See:
 
1752
     * http://trac.pjsip.org/repos/ticket/643
 
1753
     *
 
1754
     * This exception can be disabled by setting allow_contact_rewrite
 
1755
     * to 2. In this case, the switch will always be done whenever there
 
1756
     * is difference in the IP address in the response.
 
1757
     */
 
1758
    if (allowContactRewrite_ != 2 && not is_private_ip(&uri->host) and
 
1759
        not is_private_ip(&srv_ip) and is_private_ip(via_addr)) {
 
1760
        /* Don't switch */
 
1761
        return false;
 
1762
    }
 
1763
 
 
1764
    /* Also don't switch if only the port number part is different, and
 
1765
     * the Via received address is private.
 
1766
     * See http://trac.pjsip.org/repos/ticket/864
 
1767
     */
 
1768
    if (allowContactRewrite_ != 2 and pj_sockaddr_cmp(&contact_addr, &recv_addr) == 0 and
 
1769
        is_private_ip(via_addr)) {
 
1770
        /* Don't switch */
 
1771
        return false;
 
1772
    }
 
1773
 
 
1774
    WARN("IP address change detected for account %s "
 
1775
         "(%.*s:%d --> %.*s:%d). Updating registration "
 
1776
         "(using method %d)",
 
1777
         accountID_.c_str(),
 
1778
         (int) uri->host.slen,
 
1779
         uri->host.ptr,
 
1780
         uri->port,
 
1781
         (int) via_addr->slen,
 
1782
         via_addr->ptr,
 
1783
         rport,
 
1784
         contactRewriteMethod_);
 
1785
 
 
1786
    pj_assert(contactRewriteMethod_ == 1 or contactRewriteMethod_ == 2);
 
1787
 
 
1788
    if (contactRewriteMethod_ == 1) {
 
1789
        /* Unregister current contact */
 
1790
        link_->sendUnregister(this);
 
1791
        destroyRegistrationInfo();
 
1792
    }
 
1793
 
 
1794
    /*
 
1795
     * Build new Contact header
 
1796
     */
 
1797
    {
 
1798
        char *tmp;
 
1799
        const char *beginquote, *endquote;
 
1800
        char transport_param[32];
 
1801
        int len;
 
1802
 
 
1803
        /* Enclose IPv6 address in square brackets */
 
1804
        if (tp->key.type & PJSIP_TRANSPORT_IPV6) {
 
1805
            beginquote = "[";
 
1806
            endquote = "]";
 
1807
        } else {
 
1808
            beginquote = endquote = "";
 
1809
        }
 
1810
 
 
1811
        /* Don't add transport parameter if it's UDP */
 
1812
        if (tp->key.type != PJSIP_TRANSPORT_UDP and
 
1813
            tp->key.type != PJSIP_TRANSPORT_UDP6) {
 
1814
            pj_ansi_snprintf(transport_param, sizeof(transport_param),
 
1815
                 ";transport=%s",
 
1816
                 pjsip_transport_get_type_name(
 
1817
                     (pjsip_transport_type_e)tp->key.type));
 
1818
        } else {
 
1819
            transport_param[0] = '\0';
 
1820
        }
 
1821
 
 
1822
        tmp = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
 
1823
        len = pj_ansi_snprintf(tmp, PJSIP_MAX_URL_SIZE,
 
1824
                "<sip:%s%s%s%.*s%s:%d%s>",
 
1825
                username_.c_str(),
 
1826
                (not username_.empty() ?  "@" : ""),
 
1827
                beginquote,
 
1828
                (int) via_addr->slen,
 
1829
                via_addr->ptr,
 
1830
                endquote,
 
1831
                rport,
 
1832
                transport_param);
 
1833
        if (len < 1) {
 
1834
            ERROR("URI too long");
 
1835
            return false;
 
1836
        }
 
1837
 
 
1838
        pj_str_t tmp_str = {tmp, len};
 
1839
        pj_strncpy_with_null(&contact_, &tmp_str, PJSIP_MAX_URL_SIZE);
 
1840
    }
 
1841
 
 
1842
    if (contactRewriteMethod_ == 2 && regc_ != NULL)
 
1843
        pjsip_regc_update_contact(regc_, 1, &contact_);
 
1844
 
 
1845
#if 0
 
1846
    /* TODO: Perform new registration */
 
1847
    //pjsua_acc_set_registration(acc->index, PJ_TRUE);
 
1848
    /*  Perform new registration */
 
1849
    try {
 
1850
        link_->sendRegister(this);
 
1851
    } catch (const VoipLinkException &e) {
 
1852
        ERROR("%s", e.what());
 
1853
    }
 
1854
#endif
 
1855
 
 
1856
    return true;
 
1857
}
 
1858
 
 
1859
/* Auto re-registration timeout callback */
 
1860
void
 
1861
SIPAccount::autoReregTimerCb(pj_timer_heap_t * /*th*/, pj_timer_entry *te)
 
1862
{
 
1863
    std::pair<SIPAccount *, pjsip_endpoint *> *context = static_cast<std::pair<SIPAccount *, pjsip_endpoint *> *>(te->user_data);
 
1864
    SIPAccount *acc = context->first;
 
1865
    pjsip_endpoint *endpt = context->second;
 
1866
 
 
1867
    /* Check if the reregistration timer is still valid, e.g: while waiting
 
1868
     * timeout timer application might have deleted the account or disabled
 
1869
     * the auto-reregistration.
 
1870
     */
 
1871
    if (not acc->auto_rereg_.active) {
 
1872
        delete context;
 
1873
        return;
 
1874
    }
 
1875
 
 
1876
    /* Start re-registration */
 
1877
    acc->auto_rereg_.attempt_cnt++;
 
1878
    try {
 
1879
        acc->link_->sendRegister(acc);
 
1880
    } catch (const VoipLinkException &e) {
 
1881
        ERROR("%s", e.what());
 
1882
        acc->scheduleReregistration(endpt);
 
1883
    }
 
1884
    delete context;
 
1885
}
 
1886
 
 
1887
/* Schedule reregistration for specified account. Note that the first
 
1888
 * re-registration after a registration failure will be done immediately.
 
1889
 * Also note that this function should be called within PJSUA mutex.
 
1890
 */
 
1891
void
 
1892
SIPAccount::scheduleReregistration(pjsip_endpoint *endpt)
 
1893
{
 
1894
    /* Cancel any re-registration timer */
 
1895
    if (auto_rereg_.timer.id) {
 
1896
        auto_rereg_.timer.id = PJ_FALSE;
 
1897
        pjsip_endpt_cancel_timer(endpt, &auto_rereg_.timer);
 
1898
    }
 
1899
 
 
1900
    /* Update re-registration flag */
 
1901
    auto_rereg_.active = PJ_TRUE;
 
1902
 
 
1903
    /* Set up timer for reregistration */
 
1904
    auto_rereg_.timer.cb = &SIPAccount::autoReregTimerCb;
 
1905
    auto_rereg_.timer.user_data = new std::pair<SIPAccount *, pjsip_endpoint *>(this, endpt);
 
1906
 
 
1907
    /* Reregistration attempt. The first attempt will be done immediately. */
 
1908
    pj_time_val delay;
 
1909
    const int FIRST_RETRY_INTERVAL = 60;
 
1910
    const int RETRY_INTERVAL = 300;
 
1911
    delay.sec = auto_rereg_.attempt_cnt ? RETRY_INTERVAL : FIRST_RETRY_INTERVAL;
 
1912
    delay.msec = 0;
 
1913
 
 
1914
    /* Randomize interval by +/- 10 secs */
 
1915
    if (delay.sec >= 10) {
 
1916
        delay.msec = -10000 + (pj_rand() % 20000);
 
1917
    } else {
 
1918
        delay.sec = 0;
 
1919
        delay.msec = (pj_rand() % 10000);
 
1920
    }
 
1921
 
 
1922
    pj_time_val_normalize(&delay);
 
1923
 
 
1924
    WARN("Scheduling re-registration retry in %u seconds..", delay.sec);
 
1925
    auto_rereg_.timer.id = PJ_TRUE;
 
1926
    if (pjsip_endpt_schedule_timer(endpt, &auto_rereg_.timer, &delay) != PJ_SUCCESS)
 
1927
        auto_rereg_.timer.id = PJ_FALSE;
 
1928
}
 
1929
 
 
1930
void SIPAccount::updateDialogViaSentBy(pjsip_dialog *dlg)
 
1931
{
 
1932
    if (allowViaRewrite_ && via_addr_.host.slen > 0)
 
1933
        pjsip_dlg_set_via_sent_by(dlg, &via_addr_, via_tp_);
1224
1934
}