sipvoiplink.cpp 72.3 KB
Newer Older
jpbl's avatar
jpbl committed
1
/*
2
 *  Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Savoir-Faire Linux Inc.
3 4
 *
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
5
 *  Author: Yun Liu <yun.liu@savoirfairelinux.com>
6
 *  Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com>
7
 *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
8
 *
jpbl's avatar
jpbl committed
9 10
 *  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
11
 *  the Free Software Foundation; either version 3 of the License, or
jpbl's avatar
jpbl committed
12 13 14 15 16 17 18 19 20 21
 *  (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
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 23 24 25 26 27 28 29 30 31 32
 *
 *  Additional permission under GNU GPL version 3 section 7:
 *
 *  If you modify this program, or any covered work, by linking or
 *  combining it with the OpenSSL project's OpenSSL library (or a
 *  modified version of that library), containing parts covered by the
 *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
 *  grants you additional permission to convey the resulting work.
 *  Corresponding Source for a non-source form of such a combination
 *  shall include the source code for the parts of OpenSSL used as well
 *  as that of the covered work.
jpbl's avatar
jpbl committed
33
 */
Emmanuel Milou's avatar
Emmanuel Milou committed
34

35 36 37 38
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

jpbl's avatar
jpbl committed
39
#include "sipvoiplink.h"
40 41
#include "manager.h"

42
#include "sip/sdp.h"
yanmorin's avatar
 
yanmorin committed
43
#include "sipcall.h"
Emmanuel Milou's avatar
nothing  
Emmanuel Milou committed
44
#include "sipaccount.h"
45
#include "eventthread.h"
46
#include "sdes_negotiator.h"
47 48 49

#include "dbus/dbusmanager.h"
#include "dbus/callmanager.h"
50

51
#include "hooks/urlhook.h"
52
#include "im/instant_messaging.h"
53

54 55
#include "audio/audiolayer.h"

56
#include "pjsip/sip_endpoint.h"
57
#include "pjsip/sip_transport_tls.h"
58 59
#include "pjsip/sip_uri.h"
#include <pjnath.h>
60

Emmanuel Milou's avatar
Emmanuel Milou committed
61 62 63
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
64
#include <istream>
65
#include <utility> // for std::pair
Emmanuel Milou's avatar
Emmanuel Milou committed
66

67 68 69 70 71
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>

72 73
#include <map>

74 75
using namespace sfl;

76
namespace {
Rafaël Carré's avatar
Rafaël Carré committed
77

78
static pjsip_transport *localUDPTransport_ = NULL; /** The default transport (5060) */
79 80 81

/** A map to retreive SFLphone internal call id
 *  Given a SIP call ID (usefull for transaction sucha as transfer)*/
82
static std::map<std::string, std::string> transferCallID;
83

Emmanuel Milou's avatar
Emmanuel Milou committed
84
/**************** EXTERN VARIABLES AND FUNCTIONS (callbacks) **************************/
jpbl's avatar
jpbl committed
85

86
/**
87 88 89 90
 * Set audio (SDP) configuration for a call
 * localport, localip, localexternalport
 * @param call a SIPCall valid pointer
 */
91
static void setCallMediaLocal(SIPCall* call, const std::string &localIP);
92

93 94 95
/**
 * Helper function to parser header from incoming sip messages
 */
96
std::string fetchHeaderValue(pjsip_msg *msg, const std::string &field);
97

98 99 100 101
static pj_caching_pool pool_cache, *cp_ = &pool_cache;
static pj_pool_t *pool_;
static pjsip_endpoint *endpt_;
static pjsip_module mod_ua_;
102
static pj_thread_t *thread;
Emmanuel Milou's avatar
Emmanuel Milou committed
103

104 105 106 107 108 109 110 111 112
static void sdp_media_update_cb(pjsip_inv_session *inv, pj_status_t status UNUSED);
static void sdp_request_offer_cb(pjsip_inv_session *inv, const pjmedia_sdp_session *offer);
static void sdp_create_offer_cb(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer);
static void invite_session_state_changed_cb(pjsip_inv_session *inv, pjsip_event *e);
static void outgoing_request_forked_cb(pjsip_inv_session *inv, pjsip_event *e);
static void transaction_state_changed_cb(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e);
static void registration_cb(pjsip_regc_cbparam *param);
static pj_bool_t transaction_request_cb(pjsip_rx_data *rdata);
static pj_bool_t transaction_response_cb(pjsip_rx_data *rdata UNUSED) ;
Emmanuel Milou's avatar
Emmanuel Milou committed
113

114
static void transfer_client_cb(pjsip_evsub *sub, pjsip_event *event);
Emmanuel Milou's avatar
Emmanuel Milou committed
115

116 117 118 119 120 121 122
/**
 * Send a reINVITE inside an active dialog to modify its state
 * Local SDP session should be modified before calling this method
 * @param sip call
 */
int SIPSessionReinvite(SIPCall *);

123 124 125
/**
 * Helper function to process refer function on call transfer
 */
126
void onCallTransfered(pjsip_inv_session *inv, pjsip_rx_data *rdata);
Emmanuel Milou's avatar
Emmanuel Milou committed
127

Tristan Matthews's avatar
Tristan Matthews committed
128
std::string getSIPLocalIP()
129 130
{
    pj_sockaddr ip_addr;
131 132 133

    if (pj_gethostip(pj_AF_INET(), &ip_addr) == PJ_SUCCESS)
        return pj_inet_ntoa(ip_addr.ipv4.sin_addr);
Tristan Matthews's avatar
Tristan Matthews committed
134 135 136 137
    else  {
        ERROR("SIPVoIPLink: Could not get local IP");
        return "";
    }
138
}
139 140 141

pjsip_route_hdr *createRouteSet(const std::string &route, pj_pool_t *hdr_pool)
{
142 143
    int port = 0;
    std::string host;
144 145

    size_t found = route.find(":");
146

147
    if (found != std::string::npos) {
148 149
        host = route.substr(0, found);
        port = atoi(route.substr(found + 1, route.length()).c_str());
150
    } else
151 152 153 154 155
        host = route;

    pjsip_route_hdr *route_set = pjsip_route_hdr_create(hdr_pool);
    pjsip_route_hdr *routing = pjsip_route_hdr_create(hdr_pool);
    pjsip_sip_uri *url = pjsip_sip_uri_create(hdr_pool, 0);
156 157 158 159
    routing->name_addr.uri = (pjsip_uri*) url;
    pj_strdup2(hdr_pool, &url->host, host.c_str());
    url->port = port;

160
    pj_list_push_back(route_set, pjsip_hdr_clone(hdr_pool, routing));
161 162 163 164

    return route_set;
}

165 166 167 168 169 170 171 172 173 174 175
void handleIncomingOptions(pjsip_rx_data *rdata)
{
    pjsip_tx_data *tdata;

    if (pjsip_endpt_create_response(endpt_, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS)
        return;

#define ADD_HDR(hdr) do { \
    const pjsip_hdr *cap_hdr = hdr; \
    if (cap_hdr) \
    pjsip_msg_add_hdr (tdata->msg, (pjsip_hdr*) pjsip_hdr_clone (tdata->pool, cap_hdr)); \
Tristan Matthews's avatar
Tristan Matthews committed
176
} while (0)
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
#define ADD_CAP(cap) ADD_HDR(pjsip_endpt_get_capability(endpt_, cap, NULL));

    ADD_CAP(PJSIP_H_ALLOW);
    ADD_CAP(PJSIP_H_ACCEPT);
    ADD_CAP(PJSIP_H_SUPPORTED);
    ADD_HDR(pjsip_evsub_get_allow_events_hdr(NULL));

    pjsip_response_addr res_addr;
    pjsip_get_response_addr(tdata->pool, rdata, &res_addr);

    if (pjsip_endpt_send_response(endpt_, &res_addr, tdata, NULL, NULL) != PJ_SUCCESS)
        pjsip_tx_data_dec_ref(tdata);
}

pj_bool_t transaction_response_cb(pjsip_rx_data *rdata)
{
    pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);

    if (!dlg)
        return PJ_SUCCESS;

    pjsip_transaction *tsx = pjsip_rdata_get_tsx(rdata);

    if (!tsx or tsx->method.id != PJSIP_INVITE_METHOD)
        return PJ_SUCCESS;

    if (tsx->status_code / 100 == 2) {
        /**
         * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response.
         * ACK for a 2xx response must be send using this method.
         */
        pjsip_tx_data *tdata;
        pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata);
        pjsip_dlg_send_request(dlg, tdata, -1, NULL);
    }

    return PJ_SUCCESS;
}

std::string parseDisplayName(const char * buffer)
{
    const char* from_header = strstr(buffer, "From: ");

    if (!from_header)
        return "";

    std::string temp(from_header);
    size_t begin_displayName = temp.find("\"") + 1;
    size_t end_displayName = temp.rfind("\"");
    std::string displayName(temp.substr(begin_displayName, end_displayName - begin_displayName));

    static const size_t MAX_DISPLAY_NAME_SIZE = 25;
    if (displayName.size() > MAX_DISPLAY_NAME_SIZE)
        return "";

    return displayName;
}

void stripSipUriPrefix(std::string& sipUri)
{
    // Remove sip: prefix
    static const char SIP_PREFIX[] = "sip:";
    size_t found = sipUri.find(SIP_PREFIX);

    if (found != std::string::npos)
        sipUri.erase(found, found + (sizeof SIP_PREFIX) - 1);

    found = sipUri.find("@");

    if (found != std::string::npos)
        sipUri.erase(found);
}

pj_bool_t transaction_request_cb(pjsip_rx_data *rdata)
{
    pjsip_method *method = &rdata->msg_info.msg->line.req.method;

    if (method->id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg(rdata))
        return true;

    pjsip_sip_uri *sip_to_uri = (pjsip_sip_uri *) pjsip_uri_get_uri(rdata->msg_info.to->uri);
    pjsip_sip_uri *sip_from_uri = (pjsip_sip_uri *) pjsip_uri_get_uri(rdata->msg_info.from->uri);
    std::string userName(sip_to_uri->user.ptr, sip_to_uri->user.slen);
    std::string server(sip_from_uri->host.ptr, sip_from_uri->host.slen);
    std::string account_id(Manager::instance().getAccountIdFromNameAndServer(userName, server));

    std::string displayName(parseDisplayName(rdata->msg_info.msg_buf));

    if (method->id == PJSIP_OTHER_METHOD) {
        pj_str_t *str = &method->name;
        std::string request(str->ptr, str->slen);

        if (request.find("NOTIFY") != (size_t)-1) {
            int voicemail;

            if (sscanf((const char*)rdata->msg_info.msg->body->data, "Voice-Message: %d/", &voicemail) == 1 && voicemail != 0)
                Manager::instance().startVoiceMessageNotification(account_id, voicemail);
        }

        pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_OK, NULL, NULL, NULL);

        return true;
    } else if (method->id == PJSIP_OPTIONS_METHOD) {
        handleIncomingOptions(rdata);
        return true;
    } else if (method->id != PJSIP_INVITE_METHOD && method->id != PJSIP_ACK_METHOD) {
        pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL);
        return true;
    }

    SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id));

    pjmedia_sdp_session *r_sdp;
    pjsip_msg_body *body = rdata->msg_info.msg->body;

    if (!body || pjmedia_sdp_parse(rdata->tp_info.pool, (char*) body->data, body->len, &r_sdp) != PJ_SUCCESS)
        r_sdp = NULL;

    if (account->getActiveCodecs().empty()) {
        pjsip_endpt_respond_stateless(endpt_, rdata,
                                      PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL,
                                      NULL);
        return false;
    }

    // Verify that we can handle the request
    unsigned options = 0;

    if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, endpt_, NULL) != PJ_SUCCESS) {
        pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL);
        return true;
    }

    if (Manager::instance().hookPreference.getSipEnabled()) {
        std::string header_value(fetchHeaderValue(rdata->msg_info.msg, Manager::instance().hookPreference.getUrlSipField()));
        UrlHook::runAction(Manager::instance().hookPreference.getUrlCommand(), header_value);
    }

    SIPCall* call = new SIPCall(Manager::instance().getNewCallID(), Call::INCOMING, cp_);
    Manager::instance().associateCallToAccount(call->getCallId(), account_id);

    // May use the published address as well
    std::string addrToUse = SIPVoIPLink::instance()->getInterfaceAddrFromName(account->getLocalInterface());
    std::string addrSdp = account->isStunEnabled()
                          ? account->getPublishedAddress()
                          : addrToUse;

    pjsip_tpselector *tp = SIPVoIPLink::instance()->initTransportSelector(account->transport_, call->getMemoryPool());

    if (addrToUse == "0.0.0.0")
        addrToUse = getSIPLocalIP();

    if (addrSdp == "0.0.0.0")
        addrSdp = addrToUse;

    char tmp[PJSIP_MAX_URL_SIZE];
    int length = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, sip_from_uri, tmp, PJSIP_MAX_URL_SIZE);
    std::string peerNumber(tmp, length);
    stripSipUriPrefix(peerNumber);

    call->setConnectionState(Call::PROGRESSING);
    call->setPeerNumber(peerNumber);
    call->setDisplayName(displayName);
    call->initRecFilename(peerNumber);

    setCallMediaLocal(call, addrToUse);

    call->getLocalSDP()->setLocalIP(addrSdp);

    call->getAudioRtp().initAudioRtpConfig();
    call->getAudioRtp().initAudioSymmetricRtpSession();

    if (rdata->msg_info.msg->body) {
        char sdpbuffer[1000];
        int len = rdata->msg_info.msg->body->print_body(rdata->msg_info.msg->body, sdpbuffer, sizeof sdpbuffer);

        if (len == -1) // error
            len = 0;

        std::string sdpoffer(sdpbuffer, len);
        size_t start = sdpoffer.find("a=crypto:");

        // Found crypto header in SDP
        if (start != std::string::npos) {
            CryptoOffer crypto_offer;
            crypto_offer.push_back(std::string(sdpoffer.substr(start, (sdpoffer.size() - start) - 1)));

            std::vector<sfl::CryptoSuiteDefinition>localCapabilities;

            for (int i = 0; i < 3; i++)
                localCapabilities.push_back(sfl::CryptoSuites[i]);

            sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer);

            if (sdesnego.negotiate()) {
                call->getAudioRtp().setRemoteCryptoInfo(sdesnego);
                call->getAudioRtp().initLocalCryptoInfo();
            }
        }
    }

    call->getLocalSDP()->receiveOffer(r_sdp, account->getActiveCodecs());

    sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW);
    call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec));

    pjsip_dialog* dialog;

    if (pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, NULL, &dialog) != PJ_SUCCESS) {
        delete call;
        pjsip_endpt_respond_stateless(endpt_, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL);
        return false;
    }

    pjsip_inv_create_uas(dialog, rdata, call->getLocalSDP()->getLocalSdpSession(), 0, &call->inv);

    PJ_ASSERT_RETURN(pjsip_dlg_set_transport(dialog, tp) == PJ_SUCCESS, 1);

    call->inv->mod_data[mod_ua_.id] = call;

    // Check whether Replaces header is present in the request and process accordingly.
    pjsip_dialog *replaced_dlg;
    pjsip_tx_data *response;

    if (pjsip_replaces_verify_request(rdata, &replaced_dlg, PJ_FALSE, &response) != PJ_SUCCESS) {
        ERROR("Something wrong with Replaces request.");
        pjsip_endpt_respond_stateless(endpt_, rdata, 500 /* internal server error */, NULL, NULL, NULL);
    }

    // Check if call has been transfered
    pjsip_tx_data *tdata;

    if (replaced_dlg) { // If Replace header present
        // Always answer the new INVITE with 200, regardless whether
        // the replaced call is in early or confirmed state.
        if (pjsip_inv_answer(call->inv, 200, NULL, NULL, &response) == PJ_SUCCESS)
            pjsip_inv_send_msg(call->inv, response);

        // Get the INVITE session associated with the replaced dialog.
        pjsip_inv_session *replaced_inv = pjsip_dlg_get_inv_session(replaced_dlg);

        // Disconnect the "replaced" INVITE session.
        if (pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, NULL, &tdata) == PJ_SUCCESS && tdata)
            pjsip_inv_send_msg(replaced_inv, tdata);
    } else { // Prooceed with normal call flow
        PJ_ASSERT_RETURN(pjsip_inv_initial_answer(call->inv, rdata, PJSIP_SC_RINGING, NULL, NULL, &tdata) == PJ_SUCCESS, 1);
        PJ_ASSERT_RETURN(pjsip_inv_send_msg(call->inv, tdata) == PJ_SUCCESS, 1);

        call->setConnectionState(Call::RINGING);

        Manager::instance().incomingCall(call, account_id);
        Manager::instance().getAccountLink(account_id)->addCall(call);
    }

    return true;
}
433 434
} // end anonymous namespace

Emmanuel Milou's avatar
Emmanuel Milou committed
435 436
/*************************************************************************************************/

437
SIPVoIPLink::SIPVoIPLink() : transportMap_(), evThread_(new EventThread(this))
438 439
{
#define TRY(ret) do { \
440 441
    if (ret != PJ_SUCCESS) \
    throw VoipLinkException(#ret " failed"); \
Tristan Matthews's avatar
Tristan Matthews committed
442
} while (0)
443 444

    srand(time(NULL)); // to get random number for RANDOM_PORT
Emmanuel Milou's avatar
Emmanuel Milou committed
445

446 447
    TRY(pj_init());
    TRY(pjlib_util_init());
448 449
    // From 0 (min) to 6 (max)
    pj_log_set_level(Logger::getDebugMode() ? 6 : 0);
450
    TRY(pjnath_init());
451

452 453
    pj_caching_pool_init(cp_, &pj_pool_factory_default_policy, 0);
    pool_ = pj_pool_create(&cp_->factory, "sflphone", 4000, 4000, NULL);
454

455
    if (!pool_)
456
        throw VoipLinkException("UserAgent: Could not initialize memory pool");
Alexandre Savard's avatar
Alexandre Savard committed
457

458
    TRY(pjsip_endpt_create(&cp_->factory, pj_gethostname()->ptr, &endpt_));
459

Tristan Matthews's avatar
Tristan Matthews committed
460
    if (getSIPLocalIP().empty())
461 462
        throw VoipLinkException("UserAgent: Unable to determine network capabilities");

463 464 465 466
    TRY(pjsip_tsx_layer_init_module(endpt_));
    TRY(pjsip_ua_init_module(endpt_, NULL));
    TRY(pjsip_replaces_init_module(endpt_)); // See the Replaces specification in RFC 3891
    TRY(pjsip_100rel_init_module(endpt_));
467 468

    // Initialize and register sflphone module
469 470 471 472 473 474
    mod_ua_.name = pj_str((char*) PACKAGE);
    mod_ua_.id = -1;
    mod_ua_.priority = PJSIP_MOD_PRIORITY_APPLICATION;
    mod_ua_.on_rx_request = &transaction_request_cb;
    mod_ua_.on_rx_response = &transaction_response_cb;
    TRY(pjsip_endpt_register_module(endpt_, &mod_ua_));
475

476 477
    TRY(pjsip_evsub_init_module(endpt_));
    TRY(pjsip_xfer_init_module(endpt_));
478 479

    static const pjsip_inv_callback inv_cb = {
480 481 482 483 484 485 486 487
        invite_session_state_changed_cb,
        outgoing_request_forked_cb,
        transaction_state_changed_cb,
        sdp_request_offer_cb,
        sdp_create_offer_cb,
        sdp_media_update_cb,
        NULL,
        NULL,
488
    };
489
    TRY(pjsip_inv_usage_init(endpt_, &inv_cb));
490 491

    static const pj_str_t allowed[] = { { (char*) "INFO", 4}, { (char*) "REGISTER", 8}, { (char*) "OPTIONS", 7}, { (char*) "MESSAGE", 7 } };       //  //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6}
492
    pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE(allowed), allowed);
493 494

    static const pj_str_t text_plain = { (char*) "text/plain", 10 };
495
    pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, NULL, 1, &text_plain);
496 497

    static const pj_str_t accepted = { (char*) "application/sdp", 15 };
498
    pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, NULL, 1, &accepted);
499

500
    DEBUG("UserAgent: pjsip version %s for %s initialized", pj_get_version(), PJ_OS_NAME);
501

502
    TRY(pjsip_replaces_init_module(endpt_));
Tristan Matthews's avatar
Tristan Matthews committed
503
#undef TRY
504 505

    evThread_->start();
yanmorin's avatar
 
yanmorin committed
506
}
jpbl's avatar
jpbl committed
507

Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
508 509
SIPVoIPLink::~SIPVoIPLink()
{
510 511 512
    delete evThread_;
    pj_thread_join(thread);
    pj_thread_destroy(thread);
513 514

    const pj_time_val tv = {0, 10};
515 516
    pjsip_endpt_handle_events(endpt_, &tv);
    pjsip_endpt_destroy(endpt_);
517

518 519
    pj_pool_release(pool_);
    pj_caching_pool_destroy(cp_);
520 521

    pj_shutdown();
522 523
}

524
SIPVoIPLink* SIPVoIPLink::instance()
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
525
{
526 527
    static SIPVoIPLink* instance = NULL;

528 529
    if (!instance)
        instance = new SIPVoIPLink;
Emmanuel Milou's avatar
Emmanuel Milou committed
530

531
    return instance;
yanmorin's avatar
 
yanmorin committed
532 533
}

534
void SIPVoIPLink::init() {}
Emmanuel Milou's avatar
Emmanuel Milou committed
535

536
void SIPVoIPLink::terminate() {}
jpbl's avatar
jpbl committed
537

538
void
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
539 540
SIPVoIPLink::getEvent()
{
541
    static pj_thread_desc desc;
542

543
    // We have to register the external thread so it could access the pjsip frameworks
544
    if (!pj_thread_is_registered())
545
        pj_thread_register(NULL, desc, &thread);
yanmorin's avatar
 
yanmorin committed
546

Rafaël Carré's avatar
Rafaël Carré committed
547
    static const pj_time_val timeout = {0, 10};
548
    pjsip_endpt_handle_events(endpt_, &timeout);
549
}
550

551
void SIPVoIPLink::sendRegister(Account *a)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
552
{
553
    SIPAccount *account = dynamic_cast<SIPAccount*>(a);
554
    createSipTransport(account);
555

556 557
    account->setRegister(true);
    account->setRegistrationState(Trying);
558

559
    pjsip_regc *regc = account->getRegistrationInfo();
560

561
    if (pjsip_regc_create(endpt_, (void *) account, &registration_cb, &regc) != PJ_SUCCESS)
562 563 564
        throw VoipLinkException("UserAgent: Unable to create regc structure.");

    std::string srvUri(account->getServerUri());
565

566 567 568
    // std::string address, port;
    // findLocalAddressFromUri(srvUri, account->transport_, address, port);
    pj_str_t pjSrv = pj_str((char*) srvUri.c_str());
569

570
    // Generate the FROM header
571
    std::string from(account->getFromUri());
572
    pj_str_t pjFrom = pj_str((char*) from.c_str());
573

574
    // Get the contact header for this account
575
    std::string contact(account->getContactHeader());
576
    pj_str_t pjContact = pj_str((char*) contact.c_str());
577

578 579
    if (pjsip_regc_init(regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, account->getRegistrationExpire()) != PJ_SUCCESS)
        throw VoipLinkException("Unable to initialize account registration structure");
580

581
    if (!account->getServiceRoute().empty())
582
        pjsip_regc_set_route_set(regc, createRouteSet(account->getServiceRoute(), pool_));
583

584
    pjsip_regc_set_credentials(regc, account->getCredentialCount(), account->getCredInfo());
585

jpbl's avatar
jpbl committed
586

587
    pjsip_hdr hdr_list;
588 589
    pj_list_init(&hdr_list);
    std::string useragent(account->getUserAgentName());
590
    pj_str_t pJuseragent = pj_str((char*) useragent.c_str());
591
    const pj_str_t STR_USER_AGENT = { (char*) "User-Agent", 10 };
592

593
    pjsip_generic_string_hdr *h = pjsip_generic_string_hdr_create(pool_, &STR_USER_AGENT, &pJuseragent);
594 595
    pj_list_push_back(&hdr_list, (pjsip_hdr*) h);
    pjsip_regc_add_headers(regc, &hdr_list);
jpbl's avatar
jpbl committed
596

597

598
    pjsip_tx_data *tdata;
Emmanuel Milou's avatar
Emmanuel Milou committed
599

600 601
    if (pjsip_regc_register(regc, PJ_TRUE, &tdata) != PJ_SUCCESS)
        throw VoipLinkException("Unable to initialize transaction data for account registration");
Emmanuel Milou's avatar
Emmanuel Milou committed
602

603
    if (pjsip_regc_set_transport(regc, initTransportSelector(account->transport_, pool_)) != PJ_SUCCESS)
604
        throw VoipLinkException("Unable to set transport");
605

606 607
    // decrease transport's ref count, counter incrementation is managed when acquiring transport
    pjsip_transport_dec_ref(account->transport_);
608

609 610 611
    // pjsip_regc_send increment the transport ref count by one,
    if (pjsip_regc_send(regc, tdata) != PJ_SUCCESS)
        throw VoipLinkException("Unable to send account registration request");
612

613 614 615 616 617 618
    // Decrease transport's ref count, since coresponding reference counter decrementation
    // is performed in pjsip_regc_destroy. This function is never called in SFLphone as the
    // regc data structure is permanently associated to the account at first registration.
    pjsip_transport_dec_ref(account->transport_);

    account->setRegistrationInfo(regc);
619 620 621 622

    // start the periodic registration request based on Expire header
    // account determines itself if a keep alive is required
    account->startKeepAliveTimer();
623 624
}

625
void SIPVoIPLink::sendUnregister(Account *a)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
626
{
627
    SIPAccount *account = dynamic_cast<SIPAccount *>(a);
628

629
    // This may occurs if account failed to register and is in state INVALID
630
    if (!account->isRegistered()) {
631
        account->setRegistrationState(Unregistered);
632
        return;
633 634
    }

635 636 637
    // Make sure to cancel any ongoing timers before unregister
    account->stopKeepAliveTimer();

638
    pjsip_regc *regc = account->getRegistrationInfo();
639

640
    if (!regc)
641
        throw VoipLinkException("Registration structure is NULL");
642

643
    pjsip_tx_data *tdata = NULL;
644 645

    if (pjsip_regc_unregister(regc, &tdata) != PJ_SUCCESS)
646
        throw VoipLinkException("Unable to unregister sip account");
647

648
    if (pjsip_regc_send(regc, tdata) != PJ_SUCCESS)
649
        throw VoipLinkException("Unable to send request to unregister sip account");
650

651
    account->setRegister(false);
jpbl's avatar
jpbl committed
652 653
}

654 655 656 657
void SIPVoIPLink::registerKeepAliveTimer(pj_timer_entry& timer, pj_time_val& delay)
{
    pj_status_t status;

658 659
    DEBUG("UserAgent: Registering keep alive timer");

660 661 662 663
    if(timer.id == -1) {
        WARN("UserAgent: Timer already scheduled");
    }

664
    status = pjsip_endpt_schedule_timer(endpt_, &timer, &delay);
665 666 667 668 669 670 671 672 673 674 675 676
    if (status != PJ_SUCCESS) {
        ERROR("UserAgent: Could not schedule new timer in pjsip endpoint");
    }

    if(status == PJ_EINVAL) {
        ERROR("UserAgent: Invalid timer or delay entry");
    }

    if(status == PJ_EINVALIDOP) {
        ERROR("Invalid timer entry, maybe already scheduled");
    }

677 678 679 680
}

void SIPVoIPLink::cancelKeepAliveTimer(pj_timer_entry& timer)
{
681
    pjsip_endpt_cancel_timer(endpt_, &timer);
682 683
}

684
Call *SIPVoIPLink::newOutgoingCall(const std::string& id, const std::string& toUrl)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
685
{
686 687
    SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(Manager::instance().getAccountFromCall(id)));

688
    if (account == NULL) // TODO: We should investigate how we could get rid of this error and create a IP2IP call instead
689
        throw VoipLinkException("Could not get account for this call");
690

691
    SIPCall* call = new SIPCall(id, Call::OUTGOING, cp_);
Emmanuel Milou's avatar
Emmanuel Milou committed
692

693
    // If toUri is not a well formatted sip URI, use account information to process it
694
    std::string toUri;
695

696 697
    if (toUrl.find("sip:") != std::string::npos or
        toUrl.find("sips:") != std::string::npos)
698
        toUri = toUrl;
699
    else
700
        toUri = account->getToUri(toUrl);
701

702 703
    call->setPeerNumber(toUri);
    std::string localAddr(getInterfaceAddrFromName(account->getLocalInterface()));
704

705
    if (localAddr == "0.0.0.0")
Tristan Matthews's avatar
Tristan Matthews committed
706
        localAddr = getSIPLocalIP();
707

708
    setCallMediaLocal(call, localAddr);
Emmanuel Milou's avatar
Emmanuel Milou committed
709

710
    // May use the published address as well
711
    std::string addrSdp = account->isStunEnabled() ?
712 713
    account->getPublishedAddress() :
    getInterfaceAddrFromName(account->getLocalInterface());
714

715
    if (addrSdp == "0.0.0.0")
Tristan Matthews's avatar
Tristan Matthews committed
716
        addrSdp = getSIPLocalIP();
Emmanuel Milou's avatar
Emmanuel Milou committed
717

718 719 720
    // Initialize the session using ULAW as default codec in case of early media
    // The session should be ready to receive media once the first INVITE is sent, before
    // the session initialization is completed
721 722
    sfl::Codec* audiocodec = Manager::instance().audioCodecFactory.instantiateCodec(PAYLOAD_CODEC_ULAW);

723
    if (audiocodec == NULL) {
724 725
        delete call;
        throw VoipLinkException("Could not instantiate codec for early media");
726
    }
727

728
    try {
729 730 731 732
        call->getAudioRtp().initAudioRtpConfig();
        call->getAudioRtp().initAudioSymmetricRtpSession();
        call->getAudioRtp().initLocalCryptoInfo();
        call->getAudioRtp().start(static_cast<sfl::AudioCodec *>(audiocodec));
733
    } catch (...) {
734
        delete call;
735 736
        throw VoipLinkException("Could not start rtp session for early media");
    }
737

738
    call->initRecFilename(toUrl);
739

740 741
    call->getLocalSDP()->setLocalIP(addrSdp);
    call->getLocalSDP()->createOffer(account->getActiveCodecs());
742

743 744 745 746
    if (!SIPStartCall(call)) {
        delete call;
        throw VoipLinkException("Could not send outgoing INVITE request for new call");
    }
jpbl's avatar
jpbl committed
747

748
    return call;
749
}
750

751
void
752
SIPVoIPLink::answer(Call *c)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
753
{
754
    SIPCall *call = dynamic_cast<SIPCall*>(c);
755

756
    if (!call)
757
        return;
Emmanuel Lepage's avatar
Emmanuel Lepage committed
758

759
    pjsip_tx_data *tdata;
Emmanuel Lepage's avatar
Emmanuel Lepage committed
760

761 762 763 764 765
    if (pjsip_inv_answer(call->inv, PJSIP_SC_OK, NULL, NULL, &tdata) != PJ_SUCCESS)
        throw VoipLinkException("Could not init invite request answer (200 OK)");

    if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS)
        throw VoipLinkException("Could not send invite request answer (200 OK)");
766

767 768
    call->setConnectionState(Call::CONNECTED);
    call->setState(Call::ACTIVE);
Yun Liu's avatar
Yun Liu committed
769 770
}

771
void
772
SIPVoIPLink::hangup(const std::string& id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
773
{
774
    SIPCall* call = getSIPCall(id);
775

776
    std::string account_id(Manager::instance().getAccountFromCall(id));
777 778
    SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(account_id));

779
    if (account == NULL)
780
        throw VoipLinkException("Could not find account for this call");
781

782
    pjsip_inv_session *inv = call->inv;
783

784
    if (inv == NULL)
785
        throw VoipLinkException("No invite session for this call");
786

787
    // Looks for sip routes
Tristan Matthews's avatar
Tristan Matthews committed
788
    if (not account->getServiceRoute().empty()) {
789
        pjsip_route_hdr *route_set = createRouteSet(account->getServiceRoute(), inv->pool);
790
        pjsip_dlg_set_route_set(inv->dlg, route_set);
791
    }
792

793
    pjsip_tx_data *tdata = NULL;
794

795
    // User hangup current call. Notify peer
796
    if (pjsip_inv_end_session(inv, 404, NULL, &tdata) != PJ_SUCCESS || !tdata)
797
        return;
798

799
    if (pjsip_inv_send_msg(inv, tdata) != PJ_SUCCESS)
800
        return;
801

802
    // Make sure user data is NULL in callbacks
803
    inv->mod_data[mod_ua_.id] = NULL;
804

805
    if (Manager::instance().isCurrentCall(id))
806
        call->getAudioRtp().stop();
807

808
    removeCall(id);
alexandresavard's avatar
alexandresavard committed
809 810
}

811
void
812
SIPVoIPLink::peerHungup(const std::string& id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
813
{
814
    SIPCall* call = getSIPCall(id);
Alexandre Savard's avatar
Alexandre Savard committed
815

816
    // User hangup current call. Notify peer
817
    pjsip_tx_data *tdata = NULL;
818 819

    if (pjsip_inv_end_session(call->inv, 404, NULL, &tdata) != PJ_SUCCESS || !tdata)
820
        return;
821

822
    if (pjsip_inv_send_msg(call->inv, tdata) != PJ_SUCCESS)
823
        return;
824

825
    // Make sure user data is NULL in callbacks
826
    call->inv->mod_data[mod_ua_.id ] = NULL;
827

828
    if (Manager::instance().isCurrentCall(id))
829
        call->getAudioRtp().stop();
830

831
    removeCall(id);
832 833
}

834
void
835
SIPVoIPLink::onhold(const std::string& id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
836
{
837
    SIPCall *call = getSIPCall(id);
838
    call->setState(Call::HOLD);
839
    call->getAudioRtp().stop();
840 841

    Sdp *sdpSession = call->getLocalSDP();
842

843
    if (!sdpSession)
844
        throw VoipLinkException("Could not find sdp session");
845 846 847 848 849

    sdpSession->removeAttributeFromLocalAudioMedia("sendrecv");
    sdpSession->removeAttributeFromLocalAudioMedia("sendonly");
    sdpSession->addAttributeToLocalAudioMedia("sendonly");

850
    SIPSessionReinvite(call);
851 852
}

853
void
854
SIPVoIPLink::offhold(const std::string& id)
855
{
856 857 858
    SIPCall *call = getSIPCall(id);

    Sdp *sdpSession = call->getLocalSDP();
859

860
    if (sdpSession == NULL)
861
        throw VoipLinkException("Could not find sdp session");