~ubuntu-branches/ubuntu/saucy/sflphone/saucy

« back to all changes in this revision

Viewing changes to .pc/transferring_typo/sflphone-common/src/sip/sipvoiplink.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Francois Marier
  • Date: 2010-12-24 16:33:55 UTC
  • mfrom: (1.1.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20101224163355-tkvvikqxbrbav6up
Tags: 0.9.11-1
* New upstream release
* Add new build dependencies on libwebkit-dev and libyaml-dev

* Bump Standards-Version up to 3.9.1
* Bump debhelper compatibility to 8
* Patch another typo in the upstream code (lintian notice)

Show diffs side-by-side

added added

removed removed

Lines of Context:
45
45
#include "dbus/dbusmanager.h"
46
46
#include "dbus/callmanager.h"
47
47
 
 
48
#include "im/InstantMessaging.h"
 
49
 
48
50
#include "pjsip/sip_endpoint.h"
49
51
#include "pjsip/sip_transport_tls.h"
50
52
#include "pjsip/sip_transport_tls.h"
65
67
 
66
68
#define CAN_REINVITE        1
67
69
 
 
70
using namespace sfl;
 
71
 
68
72
static char * invitationStateMap[] = {
69
73
    (char*) "PJSIP_INV_STATE_NULL",
70
74
    (char*) "PJSIP_INV_STATE_CALLING",
215
219
 
216
220
void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer);
217
221
 
218
 
void on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer);
 
222
void on_create_offer (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer);
219
223
 
220
224
/*
221
225
 * Registration callback
245
249
    * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response.
246
250
    * ACK for a 2xx response must be send using this method.
247
251
    */
248
 
static void sendAck(pjsip_dialog *dlg, pjsip_rx_data *rdata);
 
252
static void sendAck (pjsip_dialog *dlg, pjsip_rx_data *rdata);
249
253
 
250
254
/*
251
255
 * Transfer callbacks
261
265
 
262
266
 
263
267
SIPVoIPLink::SIPVoIPLink (const AccountID& accountID)
264
 
        : VoIPLink (accountID)
265
 
        , _nbTryListenAddr (2)   // number of times to try to start SIP listener
266
 
        , _regPort (atoi (DEFAULT_SIP_PORT))
267
 
        , _clients (0)
 
268
    : VoIPLink (accountID)
 
269
    , _nbTryListenAddr (2)   // number of times to try to start SIP listener
 
270
    , _regPort (atoi (DEFAULT_SIP_PORT))
 
271
    , _clients (0)
268
272
{
 
273
 
 
274
    _debug ("SIPVOIPLINK");
269
275
    // to get random number for RANDOM_PORT
270
276
    srand (time (NULL));
271
277
 
277
283
 
278
284
SIPVoIPLink::~SIPVoIPLink()
279
285
{
280
 
    _debug("UserAgent: SIPVoIPLink destructor called");
 
286
    _debug ("UserAgent: SIPVoIPLink destructor called");
281
287
 
282
288
    terminate();
 
289
 
283
290
}
284
291
 
285
292
SIPVoIPLink* SIPVoIPLink::instance (const AccountID& id)
299
306
 
300
307
    if (_clients == 0) {
301
308
 
302
 
        _debug("UserAgent: No SIP account anymore, terminate SIPVoIPLink");
 
309
        _debug ("UserAgent: No SIP account anymore, terminate SIPVoIPLink");
303
310
        // terminate();
304
311
        delete SIPVoIPLink::_instance;
305
312
    }
332
339
 
333
340
    if (_evThread) {
334
341
        _debug ("UserAgent: Deleting sip eventThread");
335
 
        delete _evThread; _evThread = NULL;
 
342
        delete _evThread;
 
343
        _evThread = NULL;
336
344
    }
337
345
 
338
346
 
339
347
    /* Clean shutdown of pjsip library */
340
348
    if (initDone()) {
341
 
        _debug ("UserAgent: Shuting down PJSIP");
 
349
        _debug ("UserAgent: Shutting down PJSIP");
342
350
        pjsip_shutdown();
343
351
    }
344
352
 
345
353
    initDone (false);
 
354
 
346
355
}
347
356
 
348
357
void
370
379
void
371
380
SIPVoIPLink::terminateOneCall (const CallID& id)
372
381
{
373
 
        _debug("UserAgent: Terminate call %s", id.c_str());
 
382
    _debug ("UserAgent: Terminate call %s", id.c_str());
374
383
 
375
384
    SIPCall *call = getSIPCall (id);
376
385
 
405
414
}
406
415
 
407
416
 
408
 
std::string SIPVoIPLink::getInterfaceAddrFromName(std::string ifaceName) {
 
417
std::string SIPVoIPLink::getInterfaceAddrFromName (std::string ifaceName)
 
418
{
409
419
 
410
420
    struct ifreq ifr;
411
421
    int fd;
414
424
    struct sockaddr_in *saddr_in;
415
425
    struct in_addr *addr_in;
416
426
 
417
 
    if((fd = socket (AF_INET, SOCK_DGRAM,0)) < 0)
418
 
        _error("UserAgent: Error: could not open socket");
 
427
    if ( (fd = socket (AF_INET, SOCK_DGRAM,0)) < 0)
 
428
        _error ("UserAgent: Error: could not open socket");
419
429
 
420
430
    memset (&ifr, 0, sizeof (struct ifreq));
421
431
 
422
432
    strcpy (ifr.ifr_name, ifaceName.c_str());
423
433
    ifr.ifr_addr.sa_family = AF_INET;
424
434
 
425
 
    if((err = ioctl(fd, SIOCGIFADDR, &ifr)) < 0)
426
 
        _debug("UserAgent: Use default interface (0.0.0.0)");
427
 
    
428
 
    saddr_in = (struct sockaddr_in *)&ifr.ifr_addr;
429
 
    addr_in = &(saddr_in->sin_addr);
430
 
 
431
 
    std::string addr(pj_inet_ntoa(*((pj_in_addr*)addr_in)));
432
 
 
433
 
    close(fd);
 
435
    if ( (err = ioctl (fd, SIOCGIFADDR, &ifr)) < 0)
 
436
        _debug ("UserAgent: Use default interface (0.0.0.0)");
 
437
 
 
438
    saddr_in = (struct sockaddr_in *) &ifr.ifr_addr;
 
439
    addr_in = & (saddr_in->sin_addr);
 
440
 
 
441
    std::string addr (pj_inet_ntoa (* ( (pj_in_addr*) addr_in)));
 
442
 
 
443
    close (fd);
434
444
 
435
445
    return addr;
436
446
}
438
448
 
439
449
std::string SIPVoIPLink::get_useragent_name (const AccountID& id)
440
450
{
441
 
        /*
 
451
    /*
442
452
    useragent << PROGNAME << "/" << SFLPHONED_VERSION;
443
453
    return useragent.str();
444
 
        */
 
454
    */
 
455
 
 
456
    SIPAccount *account = (SIPAccount *) Manager::instance().getAccount (id);
 
457
 
445
458
    std::ostringstream  useragent;
446
 
        
447
 
        useragent << Manager::instance ().getConfigString (id, USERAGENT);
448
 
        if (useragent.str() == "sflphone" || useragent.str() == "")
449
 
                useragent << "/" << SFLPHONED_VERSION;
450
 
 
451
 
        return useragent.str ();
 
459
 
 
460
    useragent << account->getUseragent();
 
461
 
 
462
    if (useragent.str() == "sflphone" || useragent.str() == "")
 
463
        useragent << "/" << SFLPHONED_VERSION;
 
464
 
 
465
    return useragent.str ();
452
466
}
453
467
 
454
468
void
530
544
    }
531
545
 
532
546
 
533
 
    // Create SIP transport or get existent SIP transport from internal map 
 
547
    // Create SIP transport or get existent SIP transport from internal map
534
548
    // according to account settings, if the transport could not be created but
535
 
    // one is already set in account, use this one (most likely this is the 
536
 
    // transport we tried to create) 
537
 
    acquireTransport(account->getAccountID());
 
549
    // one is already set in account, use this one (most likely this is the
 
550
    // transport we tried to create)
 
551
    acquireTransport (account->getAccountID());
538
552
 
539
553
    if (account->getAccountTransport()) {
540
 
       _debug("Acquire transport in account registration: %s %s (refcnt=%d)",
541
 
              account->getAccountTransport()->obj_name,
542
 
              account->getAccountTransport()->info,
543
 
              (int)pj_atomic_get(account->getAccountTransport()->ref_cnt));
 
554
        _debug ("Acquire transport in account registration: %s %s (refcnt=%d)",
 
555
                account->getAccountTransport()->obj_name,
 
556
                account->getAccountTransport()->info,
 
557
                (int) pj_atomic_get (account->getAccountTransport()->ref_cnt));
544
558
    }
545
559
 
546
560
    _mutexSIP.enterMutex();
583
597
 
584
598
    std::string contactUri = account->getContactHeader (address, portStr);
585
599
 
586
 
    _debug ("sendRegister: fromUri: %s serverUri: %s contactUri: %s",
 
600
    _debug ("UserAgent: sendRegister: fromUri: %s serverUri: %s contactUri: %s",
587
601
            fromUri.c_str(),
588
602
            srvUri.c_str(),
589
603
            contactUri.c_str());
600
614
    // Initializes registration
601
615
 
602
616
    // Set Route for registration passing throught one or several proxies
 
617
    // status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value);
 
618
 
603
619
    status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value);
604
620
 
605
 
    /*
606
 
    if(!(account->getDomainName().empty())) {
607
 
 
608
 
        _error("Set route with %s", account->getHostname().c_str());
609
 
 
610
 
        pjsip_route_hdr *route_set = pjsip_route_hdr_create(_pool);
611
 
        pjsip_route_hdr *routing = pjsip_route_hdr_create(_pool);
612
 
        pjsip_sip_uri *url = pjsip_sip_uri_create(_pool, 0);
613
 
        routing->name_addr.uri = (pjsip_uri*)url;
614
 
        pj_strdup2(_pool, &url->host, account->getHostname().c_str());
615
 
 
616
 
        pj_list_push_back(&route_set, pjsip_hdr_clone(_pool, routing));
617
 
 
618
 
        status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value);
619
 
 
620
 
        pjsip_regc_set_route_set(regc, route_set);
621
 
    }
622
 
    else {
623
 
 
624
 
        status = pjsip_regc_init (regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, expire_value);
625
 
    }
626
 
    */
627
 
 
 
621
    if (! (account->getServiceRoute().empty())) {
 
622
 
 
623
        _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str());
 
624
 
 
625
        pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool);
 
626
        pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool);
 
627
        pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0);
 
628
        routing->name_addr.uri = (pjsip_uri*) url;
 
629
        pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str());
 
630
 
 
631
        pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing));
 
632
 
 
633
        pjsip_regc_set_route_set (regc, route_set);
 
634
    }
628
635
 
629
636
    if (status != PJ_SUCCESS) {
630
637
        _debug ("UserAgent: Unable to initialize account %d in sendRegister", status);
635
642
    pjsip_cred_info *cred = account->getCredInfo();
636
643
 
637
644
    int credential_count = account->getCredentialCount();
638
 
    _debug ("setting %d credentials in sendRegister", credential_count);
 
645
    _debug ("UserAgent: setting %d credentials in sendRegister", credential_count);
639
646
    pjsip_regc_set_credentials (regc, credential_count, cred);
640
647
 
641
648
    // Add User-Agent Header
649
656
    // pj_list_push_back (&hdr_list, (pjsip_hdr*) routing);
650
657
 
651
658
    pjsip_regc_add_headers (regc, &hdr_list);
652
 
    
 
659
 
653
660
    status = pjsip_regc_register (regc, PJ_TRUE, &tdata);
654
661
 
655
662
    if (status != PJ_SUCCESS) {
660
667
 
661
668
    pjsip_tpselector *tp;
662
669
 
663
 
    init_transport_selector (account->getAccountTransport (), &tp); 
664
 
    
 
670
    init_transport_selector (account->getAccountTransport (), &tp);
 
671
 
665
672
    // pjsip_regc_set_transport increments transport ref count by one
666
673
    status = pjsip_regc_set_transport (regc, tp);
667
674
 
668
 
    if(account->getAccountTransport()) {
669
 
        // decrease transport's ref count, counter icrementation is 
670
 
        // managed when acquiring transport 
671
 
        pjsip_transport_dec_ref(account->getAccountTransport ());
 
675
    if (account->getAccountTransport()) {
 
676
        // decrease transport's ref count, counter icrementation is
 
677
        // managed when acquiring transport
 
678
        pjsip_transport_dec_ref (account->getAccountTransport ());
672
679
 
673
 
        _debug("After setting the transport in account registration using transport: %s %s (refcnt=%d)",
674
 
               account->getAccountTransport()->obj_name,
675
 
               account->getAccountTransport()->info,
676
 
               (int)pj_atomic_get(account->getAccountTransport()->ref_cnt));
 
680
        _debug ("UserAgent: After setting the transport in account registration using transport: %s %s (refcnt=%d)",
 
681
                account->getAccountTransport()->obj_name,
 
682
                account->getAccountTransport()->info,
 
683
                (int) pj_atomic_get (account->getAccountTransport()->ref_cnt));
677
684
    }
678
685
 
679
686
    if (status != PJ_SUCCESS) {
683
690
    }
684
691
 
685
692
    // Send registration request
686
 
    // pjsip_regc_send increment the transport ref count by one, 
 
693
    // pjsip_regc_send increment the transport ref count by one,
687
694
    status = pjsip_regc_send (regc, tdata);
688
695
 
689
 
    if(account->getAccountTransport()) {
690
 
        // Decrease transport's ref count, since coresponding reference counter decrementation 
 
696
    if (account->getAccountTransport()) {
 
697
        // Decrease transport's ref count, since coresponding reference counter decrementation
691
698
        // is performed in pjsip_regc_destroy. This function is never called in SFLphone as the
692
699
        // regc data structure is permanently associated to the account at first registration.
693
 
        pjsip_transport_dec_ref(account->getAccountTransport ());
 
700
        pjsip_transport_dec_ref (account->getAccountTransport ());
694
701
    }
695
702
 
696
703
    if (status != PJ_SUCCESS) {
703
710
 
704
711
    account->setRegistrationInfo (regc);
705
712
 
706
 
    if(account->getAccountTransport()) {
 
713
    if (account->getAccountTransport()) {
707
714
 
708
 
        _debug("Sent account registration using transport: %s %s (refcnt=%d)",
709
 
               account->getAccountTransport()->obj_name,
710
 
               account->getAccountTransport()->info,
711
 
               (int)pj_atomic_get(account->getAccountTransport()->ref_cnt));
 
715
        _debug ("Sent account registration using transport: %s %s (refcnt=%d)",
 
716
                account->getAccountTransport()->obj_name,
 
717
                account->getAccountTransport()->info,
 
718
                (int) pj_atomic_get (account->getAccountTransport()->ref_cnt));
712
719
    }
713
720
 
714
721
    return true;
727
734
    regc = account->getRegistrationInfo();
728
735
 
729
736
    // If an transport is attached to this account, detach it and decrease reference counter
730
 
    if(account->getAccountTransport()) {
 
737
    if (account->getAccountTransport()) {
731
738
 
732
 
        _debug("Sent account unregistration using transport: %s %s (refcnt=%d)",
733
 
               account->getAccountTransport()->obj_name,
734
 
               account->getAccountTransport()->info,
735
 
               (int)pj_atomic_get(account->getAccountTransport()->ref_cnt));
 
739
        _debug ("Sent account unregistration using transport: %s %s (refcnt=%d)",
 
740
                account->getAccountTransport()->obj_name,
 
741
                account->getAccountTransport()->info,
 
742
                (int) pj_atomic_get (account->getAccountTransport()->ref_cnt));
736
743
 
737
744
    }
738
745
 
749
756
            _debug ("UserAgent: Unable to unregister regc.");
750
757
            return false;
751
758
        }
752
 
 
 
759
 
753
760
        status = pjsip_regc_send (regc, tdata);
754
761
 
755
762
        if (status != PJ_SUCCESS) {
774
781
    pj_status_t status;
775
782
    std::string localAddr, addrSdp;
776
783
 
777
 
    _debug("UserAgent: New outgoing call %s to %s", id.c_str(), toUrl.c_str());
 
784
    _debug ("UserAgent: New outgoing call %s to %s", id.c_str(), toUrl.c_str());
778
785
 
779
786
    SIPCall* call = new SIPCall (id, Call::Outgoing, _pool);
780
787
 
794
801
 
795
802
        call->setPeerNumber (toUri);
796
803
 
797
 
        localAddr = getInterfaceAddrFromName(account->getLocalInterface ());
 
804
        localAddr = getInterfaceAddrFromName (account->getLocalInterface ());
798
805
 
799
 
        _debug("UserAgent: Local address for call: %s", localAddr.c_str());
 
806
        _debug ("UserAgent: Local address for call: %s", localAddr.c_str());
800
807
 
801
808
        if (localAddr == "0.0.0.0")
802
809
            loadSIPLocalIP (&localAddr);
804
811
        setCallAudioLocal (call, localAddr);
805
812
 
806
813
        // May use the published address as well
807
 
        account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = getInterfaceAddrFromName(account->getLocalInterface ());
 
814
        account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = getInterfaceAddrFromName (account->getLocalInterface ());
808
815
 
809
816
        if (addrSdp == "0.0.0.0")
810
817
            loadSIPLocalIP (&addrSdp);
813
820
            _info ("UserAgent: Creating new rtp session");
814
821
            call->getAudioRtp()->initAudioRtpConfig (call);
815
822
            call->getAudioRtp()->initAudioRtpSession (call);
 
823
            call->getAudioRtp()->initLocalCryptoInfo (call);
816
824
        } catch (...) {
817
825
            _error ("UserAgent: Error: Failed to create rtp thread from newOutGoingCall");
818
826
        }
819
827
 
820
 
        call->initRecFileName();
 
828
        // init file name according to peer phone number
 
829
        call->initRecFileName (toUrl);
821
830
 
822
831
        _debug ("UserAgent: Try to make a call to: %s with call ID: %s", toUrl.data(), id.data());
823
832
 
868
877
 
869
878
    if (status == PJ_SUCCESS) {
870
879
 
871
 
        _debug ("SIPVoIPLink::answer:UserAgent: Negociation success! : call %s ", call->getCallId().c_str());
 
880
        _debug ("SIPVoIPLink: UserAgent: SDP Negociation success! : call %s ", call->getCallId().c_str());
872
881
        // Create and send a 200(OK) response
873
882
        status = pjsip_inv_answer (inv_session, PJSIP_SC_OK, NULL, NULL, &tdata);
874
883
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1);
889
898
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, 1);
890
899
 
891
900
        // Terminate the call
892
 
        _debug ("SIPVoIPLink::answer: fail terminate call %s ",call->getCallId().c_str());
 
901
        _debug ("SIPVoIPLink: UserAgent: SDP Negociation failed, terminate call %s ", call->getCallId().c_str());
893
902
 
894
903
        if (call->getAudioRtp())
895
904
            call->getAudioRtp()->stop ();
957
966
    pjsip_tx_data *tdata = NULL;
958
967
    SIPCall* call;
959
968
 
960
 
    _info("UserAgent: Peer hungup");
 
969
    _info ("UserAgent: Peer hungup");
961
970
 
962
971
    call = getSIPCall (id);
963
972
 
1000
1009
bool
1001
1010
SIPVoIPLink::cancel (const CallID& id)
1002
1011
{
1003
 
        _info ("UserAgent: Cancel call %s", id.c_str());
 
1012
    _info ("UserAgent: Cancel call %s", id.c_str());
1004
1013
 
1005
1014
    SIPCall* call = getSIPCall (id);
1006
1015
 
1007
1016
    if (!call) {
1008
 
        _warn("UserAgent: Error: Call doesn't exist");
 
1017
        _warn ("UserAgent: Error: Call doesn't exist");
1009
1018
        return false;
1010
1019
    }
1011
1020
 
1048
1057
    return true;
1049
1058
}
1050
1059
 
 
1060
bool
 
1061
SIPVoIPLink::sendTextMessage (sfl::InstantMessaging *module, const std::string& callID, const std::string& message, const std::string& from)
 
1062
{
 
1063
    _debug ("SipVoipLink: Send text message to %s, from %s", callID.c_str(), from.c_str());
 
1064
 
 
1065
    SIPCall *call = getSIPCall (callID);
 
1066
    pj_status_t status = !PJ_SUCCESS;
 
1067
 
 
1068
 
 
1069
    if (call) {
 
1070
        std::string formatedFrom = from;
 
1071
 
 
1072
        // add double quotes for xml formating
 
1073
        formatedFrom.insert (0,"\"");
 
1074
        formatedFrom.append ("\"");
 
1075
 
 
1076
        /* Send IM message */
 
1077
        sfl::InstantMessaging::UriList list;
 
1078
 
 
1079
        sfl::InstantMessaging::UriEntry entry;
 
1080
        entry[sfl::IM_XML_URI] = std::string (formatedFrom);
 
1081
 
 
1082
        list.push_front (entry);
 
1083
 
 
1084
        std::string formatedMessage = module->appendUriList (message, list);
 
1085
 
 
1086
        status = module->send_sip_message (call->getInvSession (), (CallID&) callID, formatedMessage);
 
1087
 
 
1088
    } else {
 
1089
        /* Notify the client of an error */
 
1090
        /*Manager::instance ().incomingMessage (        "",
 
1091
                                                                                        "sflphoned",
 
1092
                                                                                        "Unable to send a message outside a call.");*/
 
1093
    }
 
1094
 
 
1095
    return status;
 
1096
}
 
1097
 
1051
1098
int SIPVoIPLink::inv_session_reinvite (SIPCall *call, std::string direction)
1052
1099
{
1053
1100
 
1065
1112
 
1066
1113
    // Reinvite only if connected
1067
1114
    // Build the local SDP offer
1068
 
        // TODO Restore Re-Invite
 
1115
    // TODO Restore Re-Invite
1069
1116
    // status = call->getLocalSDP()->create_initial_offer();
1070
1117
 
1071
1118
    // if (status != PJ_SUCCESS)
1146
1193
    account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id));
1147
1194
 
1148
1195
    if (!account) {
1149
 
        _error("UserAgent: Error: Transfer account is null. Returning.");
 
1196
        _error ("UserAgent: Error: Transfer account is null. Returning.");
1150
1197
        return false;
1151
1198
    }
1152
1199
 
1195
1242
    }
1196
1243
 
1197
1244
    // Put SIP call id in map in order to retrieve call during transfer callback
1198
 
    std::string callidtransfer(call->getInvSession()->dlg->call_id->id.ptr, call->getInvSession()->dlg->call_id->id.slen);
1199
 
    _debug("%s", callidtransfer.c_str());
1200
 
    transferCallID.insert(std::pair<std::string, CallID>(callidtransfer, call->getCallId()));
 
1245
    std::string callidtransfer (call->getInvSession()->dlg->call_id->id.ptr, call->getInvSession()->dlg->call_id->id.slen);
 
1246
    _debug ("%s", callidtransfer.c_str());
 
1247
    transferCallID.insert (std::pair<std::string, CallID> (callidtransfer, call->getCallId()));
1201
1248
 
1202
1249
 
1203
1250
    /* Send. */
1214
1261
bool SIPVoIPLink::transferStep2 (SIPCall* call)
1215
1262
{
1216
1263
 
1217
 
        // TODO is this the best way to proceed?
1218
 
        Manager::instance().peerHungupCall(call->getCallId());
 
1264
    // TODO is this the best way to proceed?
 
1265
    Manager::instance().peerHungupCall (call->getCallId());
1219
1266
 
1220
1267
 
1221
1268
 
1229
1276
    pj_status_t status;
1230
1277
    pjsip_tx_data *tdata;
1231
1278
 
1232
 
    _debug("UserAgent: Refuse call %s", id.c_str());
 
1279
    _debug ("UserAgent: Refuse call %s", id.c_str());
1233
1280
 
1234
1281
    call = getSIPCall (id);
1235
1282
 
1257
1304
 
1258
1305
    call->getInvSession()->mod_data[getModId() ] = NULL;
1259
1306
 
 
1307
    removeCall (id);
 
1308
 
1260
1309
    terminateOneCall (id);
1261
1310
 
1262
 
    _debug("UserAgent: Refuse call completed");
 
1311
    _debug ("UserAgent: Refuse call completed");
1263
1312
 
1264
1313
    return true;
1265
1314
}
1294
1343
        return false;
1295
1344
    }
1296
1345
 
1297
 
    AccountID accountID = Manager::instance().getAccountFromCall(id);
1298
 
    SIPAccount *account = static_cast<SIPAccount *>(Manager::instance().getAccount(accountID));
 
1346
    AccountID accountID = Manager::instance().getAccountFromCall (id);
 
1347
    SIPAccount *account = static_cast<SIPAccount *> (Manager::instance().getAccount (accountID));
1299
1348
 
1300
 
    if(!account) {
1301
 
        _error ("UserAgent: Error: Account not found while sending DTMF");
1302
 
        return false;
 
1349
    if (!account) {
 
1350
        _error ("UserAgent: Error: Account not found while sending DTMF");
 
1351
        return false;
1303
1352
    }
1304
1353
 
1305
1354
    DtmfType type = account->getDtmfType();
1306
1355
 
1307
 
    if(type == OVERRTP)
1308
 
        dtmfOverRtp(call, code);
1309
 
    else if(type == SIPINFO)
1310
 
        dtmfSipInfo(call, code);
 
1356
    if (type == OVERRTP)
 
1357
        dtmfOverRtp (call, code);
 
1358
    else if (type == SIPINFO)
 
1359
        dtmfSipInfo (call, code);
1311
1360
    else {
1312
 
        _error("UserAgent: Error: Dtmf type does not exist");
1313
 
        return false;
1314
 
    }
1315
 
 
1316
 
    return true;
1317
 
}
1318
 
 
1319
 
 
1320
 
bool
1321
 
SIPVoIPLink::dtmfSipInfo(SIPCall *call, char code)
1322
 
{
1323
 
 
1324
 
        int duration;
1325
 
        const int body_len = 1000;
1326
 
        char *dtmf_body;
1327
 
        pj_status_t status;
1328
 
        pjsip_tx_data *tdata;
1329
 
        pj_str_t methodName, content;
1330
 
        pjsip_method method;
1331
 
        pjsip_media_type ctype;
1332
 
 
1333
 
 
1334
 
        duration = Manager::instance().getConfigInt (SIGNALISATION, PULSE_LENGTH);
1335
 
 
1336
 
        dtmf_body = new char[body_len];
1337
 
 
1338
 
        snprintf (dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration);
1339
 
 
1340
 
        pj_strdup2 (_pool, &methodName, "INFO");
1341
 
        pjsip_method_init_np (&method, &methodName);
1342
 
 
1343
 
        /* Create request message. */
1344
 
        status = pjsip_dlg_create_request (call->getInvSession()->dlg, &method, -1, &tdata);
1345
 
 
1346
 
        if (status != PJ_SUCCESS) {
1347
 
                _debug ("UserAgent: Unable to create INFO request -- %d", status);
1348
 
                return false;
1349
 
        }
1350
 
 
1351
 
        /* Get MIME type */
1352
 
        pj_strdup2 (_pool, &ctype.type, "application");
1353
 
 
1354
 
        pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay");
1355
 
 
1356
 
        /* Create "application/dtmf-relay" message body. */
1357
 
        pj_strdup2 (_pool, &content, dtmf_body);
1358
 
 
1359
 
        tdata->msg->body = pjsip_msg_body_create (tdata->pool, &ctype.type, &ctype.subtype, &content);
1360
 
 
1361
 
        if (tdata->msg->body == NULL) {
1362
 
                _debug ("UserAgent: Unable to create msg body!");
1363
 
                pjsip_tx_data_dec_ref (tdata);
1364
 
                return false;
1365
 
        }
1366
 
 
1367
 
        /* Send the request. */
1368
 
        status = pjsip_dlg_send_request (call->getInvSession()->dlg, tdata, getModId(), NULL);
1369
 
 
1370
 
        if (status != PJ_SUCCESS) {
1371
 
                _debug ("UserAgent: Unable to send MESSAGE request -- %d", status);
1372
 
                return false;
1373
 
        }
1374
 
 
1375
 
        return true;
1376
 
}
1377
 
 
1378
 
bool
1379
 
SIPVoIPLink::dtmfOverRtp(SIPCall* call, char code)
1380
 
{
1381
 
        call->getAudioRtp()->sendDtmfDigit(atoi(&code));
1382
 
 
1383
 
        return true;
 
1361
        _error ("UserAgent: Error: Dtmf type does not exist");
 
1362
        return false;
 
1363
    }
 
1364
 
 
1365
    return true;
 
1366
}
 
1367
 
 
1368
 
 
1369
bool
 
1370
SIPVoIPLink::dtmfSipInfo (SIPCall *call, char code)
 
1371
{
 
1372
 
 
1373
    int duration;
 
1374
    const int body_len = 1000;
 
1375
    char *dtmf_body;
 
1376
    pj_status_t status;
 
1377
    pjsip_tx_data *tdata;
 
1378
    pj_str_t methodName, content;
 
1379
    pjsip_method method;
 
1380
    pjsip_media_type ctype;
 
1381
 
 
1382
 
 
1383
    duration = Manager::instance().voipPreferences.getPulseLength();
 
1384
 
 
1385
    dtmf_body = new char[body_len];
 
1386
 
 
1387
    snprintf (dtmf_body, body_len - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration);
 
1388
 
 
1389
    pj_strdup2 (_pool, &methodName, "INFO");
 
1390
    pjsip_method_init_np (&method, &methodName);
 
1391
 
 
1392
    /* Create request message. */
 
1393
    status = pjsip_dlg_create_request (call->getInvSession()->dlg, &method, -1, &tdata);
 
1394
 
 
1395
    if (status != PJ_SUCCESS) {
 
1396
        _debug ("UserAgent: Unable to create INFO request -- %d", status);
 
1397
        return false;
 
1398
    }
 
1399
 
 
1400
    /* Get MIME type */
 
1401
    pj_strdup2 (_pool, &ctype.type, "application");
 
1402
 
 
1403
    pj_strdup2 (_pool, &ctype.subtype, "dtmf-relay");
 
1404
 
 
1405
    /* Create "application/dtmf-relay" message body. */
 
1406
    pj_strdup2 (_pool, &content, dtmf_body);
 
1407
 
 
1408
    tdata->msg->body = pjsip_msg_body_create (tdata->pool, &ctype.type, &ctype.subtype, &content);
 
1409
 
 
1410
    if (tdata->msg->body == NULL) {
 
1411
        _debug ("UserAgent: Unable to create msg body!");
 
1412
        pjsip_tx_data_dec_ref (tdata);
 
1413
        return false;
 
1414
    }
 
1415
 
 
1416
    /* Send the request. */
 
1417
    status = pjsip_dlg_send_request (call->getInvSession()->dlg, tdata, getModId(), NULL);
 
1418
 
 
1419
    if (status != PJ_SUCCESS) {
 
1420
        _debug ("UserAgent: Unable to send MESSAGE request -- %d", status);
 
1421
        return false;
 
1422
    }
 
1423
 
 
1424
    return true;
 
1425
}
 
1426
 
 
1427
bool
 
1428
SIPVoIPLink::dtmfOverRtp (SIPCall* call, char code)
 
1429
{
 
1430
    call->getAudioRtp()->sendDtmfDigit (atoi (&code));
 
1431
 
 
1432
    return true;
1384
1433
}
1385
1434
 
1386
1435
 
1407
1456
 
1408
1457
    AccountID id;
1409
1458
 
1410
 
    _debug("UserAgent: Start sip call");
 
1459
    _debug ("UserAgent: Start sip call");
1411
1460
 
1412
1461
    if (call == NULL)
1413
1462
        return false;
1471
1520
    // Create the invite session for this call
1472
1521
    status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv);
1473
1522
 
 
1523
 
 
1524
    if (! (account->getServiceRoute().empty())) {
 
1525
 
 
1526
        _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str());
 
1527
 
 
1528
        pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool);
 
1529
        pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool);
 
1530
        pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0);
 
1531
        routing->name_addr.uri = (pjsip_uri*) url;
 
1532
        pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str());
 
1533
 
 
1534
        pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing));
 
1535
 
 
1536
        pjsip_dlg_set_route_set (dialog, route_set);
 
1537
    }
 
1538
 
1474
1539
    PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
1475
1540
 
1476
1541
    // Set auth information
1496
1561
 
1497
1562
    // decrement transport's ref count
1498
1563
    // pjsip_transport_dec_ref(account->getAccountTransport());
1499
 
    
 
1564
 
1500
1565
    status = pjsip_inv_send_msg (inv, tdata);
1501
1566
 
1502
1567
    if (status != PJ_SUCCESS) {
1504
1569
        return false;
1505
1570
    }
1506
1571
 
1507
 
    if(account->getAccountTransport()) {
 
1572
    if (account->getAccountTransport()) {
1508
1573
 
1509
 
    _debug("UserAgent: Sent invite request using transport: %s %s (refcnt=%d)",
1510
 
                       account->getAccountTransport()->obj_name,
1511
 
                       account->getAccountTransport()->info,
1512
 
                       (int)pj_atomic_get(account->getAccountTransport()->ref_cnt));
 
1574
        _debug ("UserAgent: Sent invite request using transport: %s %s (refcnt=%d)",
 
1575
                account->getAccountTransport()->obj_name,
 
1576
                account->getAccountTransport()->info,
 
1577
                (int) pj_atomic_get (account->getAccountTransport()->ref_cnt));
1513
1578
    }
1514
1579
 
1515
1580
    return true;
1533
1598
void
1534
1599
SIPVoIPLink::SIPCallClosed (SIPCall *call)
1535
1600
{
1536
 
        _info("UserAgent: Closing call");
 
1601
    _info ("UserAgent: Closing call");
1537
1602
 
1538
1603
    if (!call) {
1539
 
                _warn("UserAgent: Error: CAll pointer is NULL\n");
 
1604
        _warn ("UserAgent: Error: CAll pointer is NULL\n");
1540
1605
        return;
1541
1606
    }
1542
1607
 
1575
1640
 
1576
1641
 
1577
1642
void
1578
 
SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata)
 
1643
SIPVoIPLink::SIPCallAnswered (SIPCall *call, pjsip_rx_data *rdata UNUSED)
1579
1644
{
1580
1645
 
1581
1646
    _info ("UserAgent: SIP call answered");
1617
1682
    pjsip_tx_data *tdata;
1618
1683
    std::string localAddress, addrSdp;
1619
1684
 
1620
 
    _debug("UserAgent: New IP2IP call %s to %s", id.c_str(), to.c_str());
 
1685
    _debug ("UserAgent: New IP2IP call %s to %s", id.c_str(), to.c_str());
1621
1686
 
1622
1687
    /* Create the call */
1623
1688
    call = new SIPCall (id, Call::Outgoing, _pool);
1625
1690
    if (call) {
1626
1691
 
1627
1692
        call->setCallConfiguration (Call::IPtoIP);
1628
 
        call->initRecFileName();
 
1693
 
 
1694
        // Init recfile name using to uri
 
1695
        call->initRecFileName (to);
1629
1696
 
1630
1697
        SIPAccount * account = NULL;
1631
1698
        account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (IP2IP_PROFILE));
1632
1699
 
1633
1700
        if (account == NULL) {
1634
1701
            _error ("UserAgent: Error: Account %s is null. Returning", IP2IP_PROFILE);
1635
 
            return !PJ_SUCCESS;
 
1702
            return !PJ_SUCCESS;
1636
1703
        }
1637
1704
 
1638
1705
        // Set the local address
1639
 
        localAddress = getInterfaceAddrFromName(account->getLocalInterface ());
 
1706
        localAddress = getInterfaceAddrFromName (account->getLocalInterface ());
1640
1707
        // Set SDP parameters - Set to local
1641
1708
        addrSdp = localAddress;
1642
1709
 
1645
1712
            loadSIPLocalIP (&localAddress);
1646
1713
        }
1647
1714
 
1648
 
        _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str());
 
1715
        _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str());
1649
1716
 
1650
1717
        // Local address to appear in SDP
1651
1718
        if (addrSdp == "0.0.0.0") {
1652
 
                addrSdp = localAddress;
 
1719
            addrSdp = localAddress;
1653
1720
        }
1654
1721
 
1655
 
        _debug ("UserAgent: Media Address for IP2IP call: %s", localAddress.c_str());
 
1722
        _debug ("UserAgent: Media Address for IP2IP call: %s", localAddress.c_str());
1656
1723
 
1657
1724
        // Set local address for RTP media
1658
1725
        setCallAudioLocal (call, localAddress);
1663
1730
        _debug ("UserAgent: TO uri for IP2IP call: %s", toUri.c_str());
1664
1731
 
1665
1732
        // Building the local SDP offer
1666
 
        call->getLocalSDP()->set_ip_address (addrSdp);
1667
 
        call->getLocalSDP()->create_initial_offer (account->getActiveCodecs ());
1668
 
 
 
1733
        // call->getLocalSDP()->set_ip_address (addrSdp);
 
1734
        // call->getLocalSDP()->create_initial_offer (account->getActiveCodecs ());
1669
1735
 
1670
1736
        // Audio Rtp Session must be initialized before creating initial offer in SDP session
1671
1737
        // since SDES require crypto attribute.
1672
1738
        try {
1673
 
                call->getAudioRtp()->initAudioRtpConfig (call);
1674
 
                call->getAudioRtp()->initAudioRtpSession (call);
 
1739
            call->getAudioRtp()->initAudioRtpConfig (call);
 
1740
            call->getAudioRtp()->initAudioRtpSession (call);
 
1741
            call->getAudioRtp()->initLocalCryptoInfo (call);
1675
1742
        } catch (...) {
1676
 
                _debug ("UserAgent: Unable to create RTP Session in new IP2IP call (%s:%d)", __FILE__, __LINE__);
 
1743
            _debug ("UserAgent: Unable to create RTP Session in new IP2IP call (%s:%d)", __FILE__, __LINE__);
1677
1744
        }
1678
1745
 
 
1746
        // Building the local SDP offer
 
1747
        call->getLocalSDP()->set_ip_address (addrSdp);
 
1748
        call->getLocalSDP()->create_initial_offer (account->getActiveCodecs ());
 
1749
 
1679
1750
        // Init TLS transport if enabled
1680
 
        if(account->isTlsEnabled()) {
1681
 
 
1682
 
                _debug("UserAgent: TLS enabled for IP2IP calls");
1683
 
                int at = toUri.find("@");
1684
 
                int trns = toUri.find(";transport");
1685
 
                std::string remoteAddr = toUri.substr(at+1, trns-at-1);
1686
 
 
1687
 
                if(toUri.find("sips:") != 1) {
1688
 
                        _debug("UserAgent: Error \"sips\" scheme required for TLS call");
1689
 
                        return false;
1690
 
                }
1691
 
 
1692
 
                if(createTlsTransport(account->getAccountID(), remoteAddr) != PJ_SUCCESS)
1693
 
                        return false;
 
1751
        if (account->isTlsEnabled()) {
 
1752
 
 
1753
            _debug ("UserAgent: TLS enabled for IP2IP calls");
 
1754
            int at = toUri.find ("@");
 
1755
            int trns = toUri.find (";transport");
 
1756
            std::string remoteAddr = toUri.substr (at+1, trns-at-1);
 
1757
 
 
1758
            if (toUri.find ("sips:") != 1) {
 
1759
                _debug ("UserAgent: Error \"sips\" scheme required for TLS call");
 
1760
                return false;
 
1761
            }
 
1762
 
 
1763
            if (createTlsTransport (account->getAccountID(), remoteAddr) != PJ_SUCCESS)
 
1764
                return false;
1694
1765
        }
1695
1766
 
1696
1767
        // If no transport already set, use the default one created at pjsip initialization
1697
1768
        if (account->getAccountTransport() == NULL) {
1698
 
                _debug ("UserAgent: No transport for this account, using the default one");
1699
 
                account->setAccountTransport (_localUDPTransport);
 
1769
            _debug ("UserAgent: No transport for this account, using the default one");
 
1770
            account->setAccountTransport (_localUDPTransport);
1700
1771
        }
1701
1772
 
1702
1773
        _debug ("UserAgent: Local port %i for IP2IP call", account->getLocalPort());
1710
1781
        int port = findLocalPortFromUri (toUri, account->getAccountTransport());
1711
1782
 
1712
1783
        std::stringstream ss;
1713
 
        std::string portStr;
1714
 
        ss << port;
1715
 
        ss >> portStr;
1716
 
        
1717
 
        std::string contactUri = account->getContactHeader (address, portStr);
1718
 
 
1719
 
        _debug ("UserAgent:  FROM uri: %s, TO uri: %s, CONTACT uri: %s",
1720
 
                fromUri.c_str(), toUri.c_str(), contactUri.c_str());
1721
 
 
1722
 
        pj_str_t pjFrom;
1723
 
        pj_cstr (&pjFrom, fromUri.c_str());
1724
 
 
1725
 
        pj_str_t pjTo;
1726
 
        pj_cstr (&pjTo, toUri.c_str());
1727
 
 
1728
 
        pj_str_t pjContact;
1729
 
        pj_cstr (&pjContact, contactUri.c_str());
1730
 
 
1731
 
        // Create the dialog (UAC)
1732
 
        // (Parameters are "strduped" inside this function)
1733
 
        status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog);
1734
 
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
1735
 
        
1736
 
        // Create the invite session for this call
1737
 
        status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv);
1738
 
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
1739
 
        
1740
 
        // Set the appropriate transport
1741
 
        pjsip_tpselector *tp;
1742
 
 
1743
 
        init_transport_selector (account->getAccountTransport(), &tp);
1744
 
 
1745
 
        if(!account->getAccountTransport()) {
1746
 
          _error("UserAgent: Error: Transport is NULL in IP2IP call");
1747
 
        }
1748
 
 
1749
 
        // set_transport methods increment transport's ref_count
1750
 
        status = pjsip_dlg_set_transport (dialog, tp);
1751
 
 
1752
 
        // decrement transport's ref count
1753
 
        // pjsip_transport_dec_ref(account->getAccountTransport());
1754
 
 
1755
 
        if (status != PJ_SUCCESS) {
1756
 
          _error ("UserAgent: Error: Failed to set the transport for an IP2IP call");
1757
 
          return status;
1758
 
        }
1759
 
 
1760
 
        // Associate current call in the invite session
1761
 
        inv->mod_data[getModId() ] = call;
1762
 
 
1763
 
        status = pjsip_inv_invite (inv, &tdata);
1764
 
        
1765
 
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
1766
 
                
1767
 
        // Associate current invite session in the call
1768
 
        call->setInvSession (inv);
1769
 
 
1770
 
        status = pjsip_inv_send_msg (inv, tdata);
1771
 
 
1772
 
        if (status != PJ_SUCCESS) {
1773
 
            delete call;
1774
 
            call = 0;
1775
 
            return false;
1776
 
        }
1777
 
 
1778
 
        call->setConnectionState (Call::Progressing);
1779
 
 
1780
 
        call->setState (Call::Active);
1781
 
        addCall (call);
1782
 
 
1783
 
        return true;
 
1784
        std::string portStr;
 
1785
        ss << port;
 
1786
        ss >> portStr;
 
1787
 
 
1788
        std::string contactUri = account->getContactHeader (address, portStr);
 
1789
 
 
1790
        _debug ("UserAgent:  FROM uri: %s, TO uri: %s, CONTACT uri: %s",
 
1791
                fromUri.c_str(), toUri.c_str(), contactUri.c_str());
 
1792
 
 
1793
        pj_str_t pjFrom;
 
1794
        pj_cstr (&pjFrom, fromUri.c_str());
 
1795
 
 
1796
        pj_str_t pjTo;
 
1797
        pj_cstr (&pjTo, toUri.c_str());
 
1798
 
 
1799
        pj_str_t pjContact;
 
1800
        pj_cstr (&pjContact, contactUri.c_str());
 
1801
 
 
1802
        // Create the dialog (UAC)
 
1803
        // (Parameters are "strduped" inside this function)
 
1804
        _debug ("UserAgent: Creating dialog for this call");
 
1805
        status = pjsip_dlg_create_uac (pjsip_ua_instance(), &pjFrom, &pjContact, &pjTo, NULL, &dialog);
 
1806
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
 
1807
 
 
1808
        // Create the invite session for this call
 
1809
        _debug ("UserAgent: Creating invite session for this call");
 
1810
        status = pjsip_inv_create_uac (dialog, call->getLocalSDP()->get_local_sdp_session(), 0, &inv);
 
1811
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
 
1812
 
 
1813
        if (! (account->getServiceRoute().empty())) {
 
1814
 
 
1815
            _error ("UserAgent: Set Service-Route with %s", account->getServiceRoute().c_str());
 
1816
 
 
1817
            pjsip_route_hdr *route_set = pjsip_route_hdr_create (_pool);
 
1818
            pjsip_route_hdr *routing = pjsip_route_hdr_create (_pool);
 
1819
            pjsip_sip_uri *url = pjsip_sip_uri_create (_pool, 0);
 
1820
            routing->name_addr.uri = (pjsip_uri*) url;
 
1821
            pj_strdup2 (_pool, &url->host, account->getServiceRoute().c_str());
 
1822
 
 
1823
            pj_list_push_back (&route_set, pjsip_hdr_clone (_pool, routing));
 
1824
 
 
1825
            pjsip_dlg_set_route_set (dialog, route_set);
 
1826
        }
 
1827
 
 
1828
        // Set the appropriate transport
 
1829
        pjsip_tpselector *tp;
 
1830
 
 
1831
        init_transport_selector (account->getAccountTransport(), &tp);
 
1832
 
 
1833
        if (!account->getAccountTransport()) {
 
1834
            _error ("UserAgent: Error: Transport is NULL in IP2IP call");
 
1835
        }
 
1836
 
 
1837
        // set_transport methods increment transport's ref_count
 
1838
        status = pjsip_dlg_set_transport (dialog, tp);
 
1839
 
 
1840
        // decrement transport's ref count
 
1841
        // pjsip_transport_dec_ref(account->getAccountTransport());
 
1842
 
 
1843
        if (status != PJ_SUCCESS) {
 
1844
            _error ("UserAgent: Error: Failed to set the transport for an IP2IP call");
 
1845
            return status;
 
1846
        }
 
1847
 
 
1848
        // Associate current call in the invite session
 
1849
        inv->mod_data[getModId() ] = call;
 
1850
 
 
1851
        status = pjsip_inv_invite (inv, &tdata);
 
1852
 
 
1853
        PJ_ASSERT_RETURN (status == PJ_SUCCESS, false);
 
1854
 
 
1855
        // Associate current invite session in the call
 
1856
        call->setInvSession (inv);
 
1857
 
 
1858
        status = pjsip_inv_send_msg (inv, tdata);
 
1859
 
 
1860
        if (status != PJ_SUCCESS) {
 
1861
            delete call;
 
1862
            call = 0;
 
1863
            return false;
 
1864
        }
 
1865
 
 
1866
        call->setConnectionState (Call::Progressing);
 
1867
 
 
1868
        call->setState (Call::Active);
 
1869
        addCall (call);
 
1870
 
 
1871
        return true;
1784
1872
    } else
1785
 
      return false;
 
1873
        return false;
1786
1874
}
1787
1875
 
1788
1876
 
1827
1915
    std::vector <std::string> dns_servers;
1828
1916
    int scount, i;
1829
1917
 
1830
 
    _debug("UserAgent: Enable DNS SRV resolver");
 
1918
    _debug ("UserAgent: Enable DNS SRV resolver");
1831
1919
 
1832
1920
    // Create the DNS resolver instance
1833
1921
    status = pjsip_endpt_create_resolver (endpt, &resv);
 
1922
 
1834
1923
    if (status != PJ_SUCCESS) {
1835
1924
        _error ("UserAgent: Error: Creating the DNS resolver instance");
1836
1925
        return status;
1848
1937
    }
1849
1938
 
1850
1939
    pj_str_t nameservers[scount];
 
1940
 
1851
1941
    for (i = 0; i<scount; i++) {
1852
 
                _debug("UserAgent: Server: %s", (char *)dns_servers[i].c_str());
 
1942
        _debug ("UserAgent: Server: %s", (char *) dns_servers[i].c_str());
1853
1943
        nameservers[i] = pj_str ( (char *) dns_servers[i].c_str());
1854
1944
    }
1855
1945
 
1856
1946
    // Update the name servers for the DNS resolver
1857
1947
    status = pj_dns_resolver_set_ns (resv, scount, nameservers, NULL);
 
1948
 
1858
1949
    if (status != PJ_SUCCESS) {
1859
1950
        _debug ("UserAgent: Error updating the name servers for the DNS resolver");
1860
1951
        return status;
1862
1953
 
1863
1954
    // Set the DNS resolver instance of the SIP resolver engine
1864
1955
    status = pjsip_endpt_set_resolver (endpt, resv);
 
1956
 
1865
1957
    if (status != PJ_SUCCESS) {
1866
1958
        _debug ("UserAgent: Error setting the DNS resolver instance of the SIP resolver engine");
1867
1959
        return status;
1923
2015
        return false;
1924
2016
    }
1925
2017
 
1926
 
    // Initialize default UDP transport according to 
 
2018
    // Initialize default UDP transport according to
1927
2019
    // IP to IP settings (most likely using port 5060)
1928
2020
    createDefaultSipUdpTransport();
1929
2021
 
1930
 
    // Call this method to create TLS listener 
 
2022
    // Call this method to create TLS listener
1931
2023
    createDefaultSipTlsListener();
1932
2024
 
1933
2025
    // Initialize transaction layer
1998
2090
    _debug ("UserAgent: VOIP callbacks initialized");
1999
2091
 
2000
2092
    // Add endpoint capabilities (INFO, OPTIONS, etc) for this UA
2001
 
    pj_str_t allowed[] = { { (char*) "INFO", 4}, { (char*) "REGISTER", 8}, { (char*) "OPTIONS", 7} };       //  //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6}
 
2093
    pj_str_t allowed[] = { { (char*) "INFO", 4}, { (char*) "REGISTER", 8}, { (char*) "OPTIONS", 7}, { (char*) "MESSAGE", 7 } };       //  //{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6}
2002
2094
 
2003
2095
    accepted = pj_str ( (char*) "application/sdp");
2004
2096
 
2005
2097
    // Register supported methods
2006
2098
    pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ALLOW, NULL, PJ_ARRAY_SIZE (allowed), allowed);
2007
2099
 
 
2100
    const pj_str_t STR_MIME_TEXT_PLAIN = { (char*) "text/plain", 10 };
 
2101
    pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &STR_MIME_TEXT_PLAIN);
 
2102
 
2008
2103
    // Register "application/sdp" in ACCEPT header
2009
2104
    pjsip_endpt_add_capability (_endpt, &_mod_ua, PJSIP_H_ACCEPT, NULL, 1, &accepted);
2010
2105
 
2076
2171
 
2077
2172
 
2078
2173
 
2079
 
bool SIPVoIPLink::acquireTransport(const AccountID& accountID) {
 
2174
bool SIPVoIPLink::acquireTransport (const AccountID& accountID)
 
2175
{
2080
2176
 
2081
2177
    SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID));
2082
2178
 
2083
 
    if(!account)
 
2179
    if (!account)
2084
2180
        return false;
2085
2181
 
2086
2182
 
2087
 
    // If an account is already bound to this account, decrease its reference 
2088
 
    // as it is going to change. If the same transport is selected, reference 
 
2183
    // If an account is already bound to this account, decrease its reference
 
2184
    // as it is going to change. If the same transport is selected, reference
2089
2185
    // counter will be increased
2090
 
    if(account->getAccountTransport()) {
 
2186
    if (account->getAccountTransport()) {
2091
2187
 
2092
 
        _debug("pjsip_transport_dec_ref in acquireTransport");
2093
 
        pjsip_transport_dec_ref(account->getAccountTransport());
 
2188
        _debug ("pjsip_transport_dec_ref in acquireTransport");
 
2189
        pjsip_transport_dec_ref (account->getAccountTransport());
2094
2190
    }
2095
2191
 
2096
2192
    // Try to create a new transport in case the settings for this account
2097
2193
    // are different than one defined for already created ones
2098
2194
    // If TLS is enabled, TLS connection is automatically handled when sending account registration
2099
 
    // However, for any other sip transaction, we must create TLS connection 
2100
 
    if(createSipTransport(accountID)) {
 
2195
    // However, for any other sip transaction, we must create TLS connection
 
2196
    if (createSipTransport (accountID)) {
2101
2197
        return true;
2102
2198
    }
2103
2199
    // A transport is already created on this port, use it
2104
2200
    else {
2105
2201
 
2106
 
        _debug("Could not create a new transport (%s)", account->getTransportMapKey().c_str());
2107
 
        _debug("Searching transport (%s) in transport map", account->getTransportMapKey().c_str());
 
2202
        _debug ("Could not create a new transport (%s)", account->getTransportMapKey().c_str());
 
2203
        _debug ("Searching transport (%s) in transport map", account->getTransportMapKey().c_str());
2108
2204
 
2109
2205
        // Could not create new transport, this transport may already exists
2110
2206
        SipTransportMap::iterator transport;
2111
 
        transport = _transportMap.find(account->getTransportMapKey());
2112
 
 
2113
 
        if(transport != _transportMap.end()) {
2114
 
 
2115
 
            // Transport already exist, use it for this account
2116
 
            _debug("Found transport (%s) in transport map", account->getTransportMapKey().c_str());
2117
 
 
2118
 
            pjsip_transport* tr = transport->second;
2119
 
 
2120
 
            // Set transport to be used for transaction involving this account
2121
 
            account->setAccountTransport(tr);
2122
 
 
2123
 
            // Increment newly associated transport reference counter
2124
 
            // If the account is shutdowning, time is automatically canceled
2125
 
            pjsip_transport_add_ref(tr);
2126
 
 
2127
 
            return true;
2128
 
        }
2129
 
        else {
2130
 
 
2131
 
            // Transport could not either be created, socket not available
2132
 
            _debug("Did not find transport (%s) in transport map", account->getTransportMapKey().c_str());
2133
 
 
2134
 
            account->setAccountTransport(_localUDPTransport);
2135
 
 
2136
 
            std::string localHostName(_localUDPTransport->local_name.host.ptr, _localUDPTransport->local_name.host.slen);
2137
 
 
2138
 
            _debug("Use default one instead (%s:%i)", localHostName.c_str(), _localUDPTransport->local_name.port);
2139
 
 
2140
 
            // account->setLocalAddress(localHostName);
2141
 
            account->setLocalPort(_localUDPTransport->local_name.port);
2142
 
 
2143
 
            // Transport could not either be created or found in the map, socket not available
2144
 
            return false;
2145
 
        }
 
2207
        transport = _transportMap.find (account->getTransportMapKey());
 
2208
 
 
2209
        if (transport != _transportMap.end()) {
 
2210
 
 
2211
            // Transport already exist, use it for this account
 
2212
            _debug ("Found transport (%s) in transport map", account->getTransportMapKey().c_str());
 
2213
 
 
2214
            pjsip_transport* tr = transport->second;
 
2215
 
 
2216
            // Set transport to be used for transaction involving this account
 
2217
            account->setAccountTransport (tr);
 
2218
 
 
2219
            // Increment newly associated transport reference counter
 
2220
            // If the account is shutdowning, time is automatically canceled
 
2221
            pjsip_transport_add_ref (tr);
 
2222
 
 
2223
            return true;
 
2224
        } else {
 
2225
 
 
2226
            // Transport could not either be created, socket not available
 
2227
            _debug ("Did not find transport (%s) in transport map", account->getTransportMapKey().c_str());
 
2228
 
 
2229
            account->setAccountTransport (_localUDPTransport);
 
2230
 
 
2231
            std::string localHostName (_localUDPTransport->local_name.host.ptr, _localUDPTransport->local_name.host.slen);
 
2232
 
 
2233
            _debug ("Use default one instead (%s:%i)", localHostName.c_str(), _localUDPTransport->local_name.port);
 
2234
 
 
2235
            // account->setLocalAddress(localHostName);
 
2236
            account->setLocalPort (_localUDPTransport->local_name.port);
 
2237
 
 
2238
            // Transport could not either be created or found in the map, socket not available
 
2239
            return false;
 
2240
        }
2146
2241
    }
2147
2242
}
2148
2243
 
2160
2255
 
2161
2256
    // Create a UDP listener meant for all accounts for which TLS was not enabled
2162
2257
    // Cannot acquireTransport since default UDP transport must be created regardless of TLS
2163
 
    errPjsip = createUdpTransport(IP2IP_PROFILE);
 
2258
    errPjsip = createUdpTransport (IP2IP_PROFILE);
2164
2259
 
2165
 
    if(account && (errPjsip == PJ_SUCCESS)) {
 
2260
    if (account && (errPjsip == PJ_SUCCESS)) {
2166
2261
 
2167
2262
        // Store transport in transport map
2168
 
        addTransportToMap(account->getTransportMapKey(), account->getAccountTransport());
2169
 
 
2170
 
        // if account is not NULL, use IP2IP trasport as default one
2171
 
        _localUDPTransport = account->getAccountTransport();
2172
 
 
 
2263
        addTransportToMap (account->getTransportMapKey(), account->getAccountTransport());
 
2264
 
 
2265
        // if account is not NULL, use IP2IP trasport as default one
 
2266
        _localUDPTransport = account->getAccountTransport();
 
2267
 
2173
2268
    }
2174
2269
    // If the above UDP server
2175
2270
    // could not be created, then give it another try
2179
2274
        _regPort = RANDOM_SIP_PORT;
2180
2275
 
2181
2276
        _debug ("UserAgent: Trying to initialize SIP listener on port %d", _regPort);
2182
 
        // If no AccountID specified, pointer to transport is stored in _localUDPTransport 
 
2277
        // If no AccountID specified, pointer to transport is stored in _localUDPTransport
2183
2278
        errPjsip = createUdpTransport();
2184
2279
 
2185
2280
        if (errPjsip != PJ_SUCCESS) {
2186
2281
            _debug ("UserAgent: Fail to initialize SIP listener on port %d", _regPort);
2187
 
            return false;
 
2282
            return false;
2188
2283
        }
2189
2284
    }
2190
2285
 
2199
2294
    SIPAccount * account = NULL;
2200
2295
    account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (IP2IP_PROFILE));
2201
2296
 
2202
 
    if(account->isTlsEnabled()) {
2203
 
        createTlsListener(IP2IP_PROFILE);
 
2297
    if (account->isTlsEnabled()) {
 
2298
        createTlsListener (IP2IP_PROFILE);
2204
2299
    }
2205
2300
}
2206
2301
 
2207
2302
 
2208
 
void SIPVoIPLink::createTlsListener(const AccountID& accountID)
 
2303
void SIPVoIPLink::createTlsListener (const AccountID& accountID)
2209
2304
{
2210
2305
 
2211
2306
    pjsip_tpfactory *tls;
2214
2309
    pj_status_t status;
2215
2310
    pj_status_t success;
2216
2311
 
2217
 
    _debug("Create TLS listener");
 
2312
    _debug ("Create TLS listener");
2218
2313
 
2219
2314
    /* Grab the tls settings, populated
2220
2315
     * from configuration file.
2232
2327
    pj_sockaddr_in_init (&local_addr, 0, 0);
2233
2328
    pj_uint16_t localTlsPort = account->getTlsListenerPort();
2234
2329
    local_addr.sin_port = pj_htons (localTlsPort);
2235
 
     
 
2330
 
2236
2331
    pj_str_t pjAddress;
2237
2332
    pj_cstr (&pjAddress, PJ_INADDR_ANY);
2238
2333
    success = pj_sockaddr_in_set_str_addr (&local_addr, &pjAddress);
2240
2335
 
2241
2336
    // Init published address for this listener (Local IP address on port 5061)
2242
2337
    std::string publishedAddress;
2243
 
    loadSIPLocalIP(&publishedAddress);
 
2338
    loadSIPLocalIP (&publishedAddress);
2244
2339
 
2245
2340
    pj_bzero (&a_name, sizeof (pjsip_host_port));
2246
2341
    pj_cstr (&a_name.host, publishedAddress.c_str());
2249
2344
    /* Get TLS settings. Expected to be filled */
2250
2345
    pjsip_tls_setting * tls_setting = account->getTlsSetting();
2251
2346
 
2252
 
    
 
2347
 
2253
2348
    _debug ("UserAgent: TLS transport to be initialized with published address %.*s,"
2254
 
            " published port %d,\n                  local address %.*s, local port %d",
2255
 
            (int) a_name.host.slen, a_name.host.ptr,
2256
 
            (int) a_name.port, pjAddress.slen, pjAddress.ptr, (int) localTlsPort);
2257
 
    
 
2349
    " published port %d,\n                  local address %.*s, local port %d",
 
2350
    (int) a_name.host.slen, a_name.host.ptr,
 
2351
    (int) a_name.port, pjAddress.slen, pjAddress.ptr, (int) localTlsPort);
 
2352
 
2258
2353
 
2259
2354
    status = pjsip_tls_transport_start (_endpt, tls_setting, &local_addr, &a_name, 1, &tls);
2260
2355
 
2261
2356
    if (status != PJ_SUCCESS) {
2262
2357
        _debug ("UserAgent: Error creating SIP TLS listener (%d)", status);
2263
 
    }
2264
 
    else {
 
2358
    } else {
2265
2359
        _localTlsListener = tls;
2266
2360
    }
2267
 
    
 
2361
 
2268
2362
    // return PJ_SUCCESS;
2269
 
    
 
2363
 
2270
2364
}
2271
2365
 
2272
2366
 
2273
 
bool SIPVoIPLink::createSipTransport(AccountID id)
 
2367
bool SIPVoIPLink::createSipTransport (AccountID id)
2274
2368
{
2275
2369
 
2276
2370
    SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (id));
2282
2376
 
2283
2377
    if (account->isTlsEnabled()) {
2284
2378
 
2285
 
        if(_localTlsListener == NULL)
2286
 
            createTlsListener(id);
 
2379
        if (_localTlsListener == NULL)
 
2380
            createTlsListener (id);
2287
2381
 
2288
 
        // Parse remote address to establish connection 
 
2382
        // Parse remote address to establish connection
2289
2383
        std::string remoteSipUri = account->getServerUri();
2290
 
        int sips = remoteSipUri.find("<sips:") + 6;
2291
 
        int trns = remoteSipUri.find(";transport");
2292
 
        std::string remoteAddr = remoteSipUri.substr(sips, trns-sips);
 
2384
        int sips = remoteSipUri.find ("<sips:") + 6;
 
2385
        int trns = remoteSipUri.find (";transport");
 
2386
        std::string remoteAddr = remoteSipUri.substr (sips, trns-sips);
2293
2387
 
2294
2388
        // Nothing to do, TLS listener already created at pjsip's startup and TLS connection
2295
2389
        // is automatically handled in pjsip when sending registration messages.
2296
 
        if(createTlsTransport(id, remoteAddr) != PJ_SUCCESS)
2297
 
            return false;
 
2390
        if (createTlsTransport (id, remoteAddr) != PJ_SUCCESS)
 
2391
            return false;
2298
2392
 
2299
2393
        return true;
2300
 
    }
2301
 
    else {
 
2394
    } else {
2302
2395
 
2303
2396
        // Launch a new UDP listener/transport, using the published address
2304
2397
        if (account->isStunEnabled ()) {
2307
2400
 
2308
2401
            if (status != PJ_SUCCESS) {
2309
2402
                _debug ("Failed to init UDP transport with STUN published address for account %s", id.c_str());
2310
 
                return false;
 
2403
                return false;
2311
2404
            }
2312
2405
 
2313
2406
        } else {
2314
2407
 
2315
2408
            status = createUdpTransport (id);
2316
2409
 
2317
 
            if (status != PJ_SUCCESS) {
 
2410
            if (status != PJ_SUCCESS) {
2318
2411
                _debug ("Failed to initialize UDP transport for account %s", id.c_str());
2319
 
                return false;
2320
 
            }
2321
 
            else {
 
2412
                return false;
 
2413
            } else {
2322
2414
 
2323
 
                // If transport succesfully created, store it in the internal map.
2324
 
                // STUN aware transport are account specific and should not be stored in map.
2325
 
                // TLS transport is ephemeral and is managed by PJSIP, should not be stored either.
2326
 
                addTransportToMap(account->getTransportMapKey(), account->getAccountTransport());
2327
 
            }
2328
 
        }
 
2415
                // If transport successfully created, store it in the internal map.
 
2416
                // STUN aware transport are account specific and should not be stored in map.
 
2417
                // TLS transport is ephemeral and is managed by PJSIP, should not be stored either.
 
2418
                addTransportToMap (account->getTransportMapKey(), account->getAccountTransport());
 
2419
            }
 
2420
        }
2329
2421
    }
2330
2422
 
2331
 
    return true;   
 
2423
    return true;
2332
2424
}
2333
 
   
2334
 
 
2335
 
 
2336
 
bool SIPVoIPLink::addTransportToMap(std::string key, pjsip_transport* transport)
 
2425
 
 
2426
 
 
2427
 
 
2428
bool SIPVoIPLink::addTransportToMap (std::string key, pjsip_transport* transport)
2337
2429
{
2338
2430
 
2339
2431
    SipTransportMap::iterator iter_transport;
2340
 
    iter_transport = _transportMap.find(key);
2341
 
        
 
2432
    iter_transport = _transportMap.find (key);
 
2433
 
2342
2434
    // old transport in transport map, erase it
2343
 
    if(iter_transport != _transportMap.end()){
2344
 
        _transportMap.erase(iter_transport);
 
2435
    if (iter_transport != _transportMap.end()) {
 
2436
        _transportMap.erase (iter_transport);
2345
2437
    }
2346
2438
 
2347
 
    _debug("UserAgent: Storing newly created transport in map using key %s", key.c_str());
2348
 
    _transportMap.insert(pair<std::string, pjsip_transport*>(key, transport));
 
2439
    _debug ("UserAgent: Storing newly created transport in map using key %s", key.c_str());
 
2440
    _transportMap.insert (pair<std::string, pjsip_transport*> (key, transport));
2349
2441
 
2350
2442
    return true;
2351
2443
 
2360
2452
    pjsip_host_port a_name;
2361
2453
    // char tmpIP[32];
2362
2454
    pjsip_transport *transport;
2363
 
    std::string listeningAddress = "127.0.0.1";
 
2455
    std::string listeningAddress = "0.0.0.0";
2364
2456
    int listeningPort = _regPort;
2365
2457
 
2366
2458
    /* Use my local address as default value */
2388
2480
    } else {
2389
2481
 
2390
2482
        // We are trying to initialize a UDP transport available for all local accounts and direct IP calls
2391
 
        _debug("UserAgent: found account %s in map", account->getAccountID().c_str());
 
2483
        _debug ("UserAgent: found account %s in map", account->getAccountID().c_str());
2392
2484
 
2393
2485
        if (account->getLocalInterface () != "default") {
2394
 
            listeningAddress = getInterfaceAddrFromName(account->getLocalInterface());
 
2486
            listeningAddress = getInterfaceAddrFromName (account->getLocalInterface());
2395
2487
        }
2396
2488
 
2397
2489
        listeningPort = account->getLocalPort ();
2405
2497
 
2406
2498
        // Init bound address to ANY
2407
2499
        bound_addr.sin_addr.s_addr = pj_htonl (PJ_INADDR_ANY);
2408
 
    }
2409
 
    else {
 
2500
        loadSIPLocalIP (&listeningAddress);
 
2501
    } else {
2410
2502
 
2411
 
        // bind this account to a specific interface        
2412
 
        pj_strdup2(_pool, &temporary_address, listeningAddress.c_str());
2413
 
        bound_addr.sin_addr = pj_inet_addr(&temporary_address);
 
2503
        // bind this account to a specific interface
 
2504
        pj_strdup2 (_pool, &temporary_address, listeningAddress.c_str());
 
2505
        bound_addr.sin_addr = pj_inet_addr (&temporary_address);
2414
2506
    }
2415
2507
 
2416
2508
    bound_addr.sin_port = pj_htons ( (pj_uint16_t) listeningPort);
2419
2511
 
2420
2512
    // Create UDP-Server (default port: 5060)
2421
2513
    // Use here either the local information or the published address
2422
 
    if (account != NULL && !account->getPublishedSameasLocal ()) {
 
2514
    if (account && !account->getPublishedSameasLocal ()) {
2423
2515
 
2424
2516
        // Set the listening address to the published address
2425
2517
        listeningAddress = account->getPublishedAddress ();
 
2518
 
2426
2519
        // Set the listening port to the published port
2427
2520
        listeningPort = account->getPublishedPort ();
2428
2521
        _debug ("UserAgent: Creating UDP transport published %s:%i", listeningAddress.c_str (), listeningPort);
2429
2522
 
2430
2523
    }
2431
2524
 
2432
 
    if(listeningAddress == "" || listeningPort == 0) {
2433
 
        _error("UserAgent: Error invalid address for new udp transport");
2434
 
        return !PJ_SUCCESS;
 
2525
    // We must specify this here to avoid the IP2IP_PROFILE
 
2526
    // to create a transport with name 0.0.0.0 to appear in the via header
 
2527
    if (id == IP2IP_PROFILE)
 
2528
        loadSIPLocalIP (&listeningAddress);
 
2529
 
 
2530
    if (listeningAddress == "" || listeningPort == 0) {
 
2531
        _error ("UserAgent: Error invalid address for new udp transport");
 
2532
        return !PJ_SUCCESS;
2435
2533
    }
 
2534
 
2436
2535
    //strcpy (tmpIP, listeningAddress.data());
2437
2536
    /* Init published name */
2438
2537
    pj_bzero (&a_name, sizeof (pjsip_host_port));
2459
2558
 
2460
2559
        if (account == NULL) {
2461
2560
 
2462
 
            _debug("UserAgent: Use transport as local UDP server");
 
2561
            _debug ("UserAgent: Use transport as local UDP server");
2463
2562
            _localUDPTransport = transport;
2464
 
        }
2465
 
        else {
 
2563
        } else {
2466
2564
 
2467
 
            _debug("UserAgent: bind transport to account %s", account->getAccountID().c_str());
2468
 
            account->setAccountTransport (transport);
2469
 
        }
 
2565
            _debug ("UserAgent: bind transport to account %s", account->getAccountID().c_str());
 
2566
            account->setAccountTransport (transport);
 
2567
        }
2470
2568
    }
2471
2569
 
2472
2570
    return PJ_SUCCESS;
2534
2632
    pj_status_t status;
2535
2633
 
2536
2634
    /* Init the transport selector */
 
2635
 
2537
2636
    //_debug ("Transport ID: %s", transport->obj_name);
2538
2637
    if (transportType == PJSIP_TRANSPORT_UDP) {
2539
2638
        status = init_transport_selector (transport, &tp_sel);
2540
2639
 
2541
2640
        if (status == PJ_SUCCESS) {
2542
2641
            status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, tp_sel, &localAddress, &port);
2543
 
        }
2544
 
        else {
2545
 
                status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port);
2546
 
        }
2547
 
    }
2548
 
    else {
 
2642
        } else {
 
2643
            status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port);
 
2644
        }
 
2645
    } else {
2549
2646
        status = pjsip_tpmgr_find_local_addr (tpmgr, _pool, transportType, NULL, &localAddress, &port);
2550
2647
    }
2551
2648
 
2554
2651
        return machineName;
2555
2652
    }
2556
2653
 
2557
 
        std::string localaddr(localAddress.ptr, localAddress.slen);
 
2654
    std::string localaddr (localAddress.ptr, localAddress.slen);
 
2655
 
 
2656
    if (localaddr == "0.0.0.0")
 
2657
        loadSIPLocalIP (&localaddr);
 
2658
 
2558
2659
    _debug ("SIP: Local address discovered from attached transport: %s", localaddr.c_str());
2559
2660
 
2560
 
    return std::string (localAddress.ptr, localAddress.slen);
 
2661
    return localaddr;
2561
2662
}
2562
2663
 
2563
2664
 
2659
2760
}
2660
2761
 
2661
2762
 
2662
 
pj_status_t SIPVoIPLink::createTlsTransport(const AccountID& accountID, std::string remoteAddr)
 
2763
pj_status_t SIPVoIPLink::createTlsTransport (const AccountID& accountID, std::string remoteAddr)
2663
2764
{
2664
2765
    pj_status_t success;
2665
2766
 
2666
 
    _debug("Create TLS transport for account %s\n", accountID.c_str());
 
2767
    _debug ("Create TLS transport for account %s\n", accountID.c_str());
2667
2768
 
2668
2769
    // Retrieve the account information
2669
2770
    SIPAccount * account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID));
2670
2771
 
2671
 
    if(!account) {
2672
 
        _debug("UserAgent: Account is NULL when creating TLS connection, returning");
2673
 
        return !PJ_SUCCESS;
 
2772
    if (!account) {
 
2773
        _debug ("UserAgent: Account is NULL when creating TLS connection, returning");
 
2774
        return !PJ_SUCCESS;
2674
2775
    }
2675
2776
 
2676
2777
    pj_sockaddr_in rem_addr;
2677
2778
    pj_str_t remote;
2678
2779
 
2679
 
    pj_cstr(&remote, remoteAddr.c_str());
 
2780
    pj_cstr (&remote, remoteAddr.c_str());
2680
2781
 
2681
 
    pj_sockaddr_in_init(&rem_addr, &remote, (pj_uint16_t)5061);
 
2782
    pj_sockaddr_in_init (&rem_addr, &remote, (pj_uint16_t) 5061);
2682
2783
 
2683
2784
    // Update TLS settings for account registration using the default listeners
2684
2785
    // Pjsip does not allow to create multiple listener
2687
2788
 
2688
2789
    // Create a new TLS connection from TLS listener
2689
2790
    pjsip_transport *tls;
2690
 
    success = pjsip_endpt_acquire_transport(_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof(rem_addr), NULL, &tls);
 
2791
    success = pjsip_endpt_acquire_transport (_endpt, PJSIP_TRANSPORT_TLS, &rem_addr, sizeof (rem_addr), NULL, &tls);
2691
2792
 
2692
 
    if(success != PJ_SUCCESS)
2693
 
        _debug("UserAgent: Error could not create TLS transport");
2694
 
    else 
2695
 
        account->setAccountTransport(tls);
 
2793
    if (success != PJ_SUCCESS)
 
2794
        _debug ("UserAgent: Error could not create TLS transport");
 
2795
    else
 
2796
        account->setAccountTransport (tls);
2696
2797
 
2697
2798
    return success;
2698
2799
}
2787
2888
 
2788
2889
    account->setAccountTransport (transport);
2789
2890
 
2790
 
    if(transport) {
2791
 
 
2792
 
        _debug("UserAgent: Initial ref count: %s %s (refcnt=%i)", transport->obj_name, transport->info,
2793
 
                                        (int)pj_atomic_get(transport->ref_cnt));
2794
 
 
2795
 
        pj_sockaddr *addr = (pj_sockaddr*)&(transport->key.rem_addr);
2796
 
 
2797
 
        static char str[PJ_INET6_ADDRSTRLEN];
2798
 
        pj_inet_ntop(((const pj_sockaddr*)addr)->addr.sa_family, pj_sockaddr_get_addr(addr), str, sizeof(str));
2799
 
    
2800
 
    
2801
 
        _debug("UserAgent: KEY: %s:%d",str, pj_sockaddr_get_port((const pj_sockaddr*)&(transport->key.rem_addr)));
 
2891
    if (transport) {
 
2892
 
 
2893
        _debug ("UserAgent: Initial ref count: %s %s (refcnt=%i)", transport->obj_name, transport->info,
 
2894
        (int) pj_atomic_get (transport->ref_cnt));
 
2895
 
 
2896
        pj_sockaddr *addr = (pj_sockaddr*) & (transport->key.rem_addr);
 
2897
 
 
2898
        static char str[PJ_INET6_ADDRSTRLEN];
 
2899
        pj_inet_ntop ( ( (const pj_sockaddr*) addr)->addr.sa_family, pj_sockaddr_get_addr (addr), str, sizeof (str));
 
2900
 
 
2901
 
 
2902
        _debug ("UserAgent: KEY: %s:%d",str, pj_sockaddr_get_port ( (const pj_sockaddr*) & (transport->key.rem_addr)));
2802
2903
 
2803
2904
    }
2804
2905
 
2810
2911
}
2811
2912
 
2812
2913
 
2813
 
void SIPVoIPLink::shutdownSipTransport(const AccountID& accountID)
 
2914
void SIPVoIPLink::shutdownSipTransport (const AccountID& accountID)
2814
2915
{
2815
2916
 
2816
 
    _debug("UserAgent: Shutdown Sip Transport");
 
2917
    _debug ("UserAgent: Shutdown Sip Transport");
2817
2918
 
2818
2919
    SIPAccount* account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountID));
2819
2920
 
2820
 
    if(!account)
 
2921
    if (!account)
2821
2922
        return;
2822
2923
 
2823
 
    if(account->getAccountTransport()) {
2824
 
 
2825
 
        _debug("Transport bound to account, decrease ref count");
2826
 
 
2827
 
        // decrease reference count added by pjsip_regc_send
2828
 
        // PJSIP's IDLE timer is set if counter reach 0
 
2924
    if (account->getAccountTransport()) {
 
2925
 
 
2926
        _debug ("Transport bound to account, decrease ref count");
 
2927
 
 
2928
        // decrease reference count added by pjsip_regc_send
 
2929
        // PJSIP's IDLE timer is set if counter reach 0
2829
2930
 
2830
2931
        // there is still problems when account registration fails, so comment it for now
2831
 
        // status = pjsip_transport_dec_ref(account->getAccountTransport());
 
2932
        // status = pjsip_transport_dec_ref(account->getAccountTransport());
2832
2933
 
2833
 
        // detach transport from this account
2834
 
        account->setAccountTransport(NULL);
 
2934
        // detach transport from this account
 
2935
        account->setAccountTransport (NULL);
2835
2936
 
2836
2937
    }
2837
2938
 
2917
3018
    /* Shutdown PJLIB */
2918
3019
    pj_shutdown();
2919
3020
 
2920
 
    _debug ("UserAgent: Shutted down succesfully");
 
3021
    _debug ("UserAgent: Shutted down successfully");
2921
3022
 
2922
3023
    /* Done. */
2923
3024
    return true;
2976
3077
        Manager::instance().startVoiceMessageNotification (account, voicemail);
2977
3078
}
2978
3079
 
2979
 
void SIPVoIPLink::handle_reinvite (SIPCall *call)
 
3080
void SIPVoIPLink::handle_reinvite (SIPCall *call UNUSED)
2980
3081
{
2981
 
 
2982
3082
    _debug ("UserAgent: Handle reinvite");
2983
 
    /*
2984
 
    // Close the previous RTP session
2985
 
    call->getAudioRtp()->stop ();
2986
 
    call->setAudioStart (false);
2987
 
    
2988
 
    _debug ("Create new rtp session from handle_reinvite : %s:%i", call->getLocalIp().c_str(), call->getLocalAudioPort());
2989
 
    _debug ("UserAgent: handle_reinvite");
2990
 
 
2991
 
    try {
2992
 
        call->getAudioRtp()->initAudioRtpSession (call);
2993
 
    } catch (...) {
2994
 
        _debug ("! SIP Failure: Unable to create RTP Session (%s:%d)", __FILE__, __LINE__);
2995
 
    }
2996
 
  
2997
 
    
2998
 
    _debug("Handle reINVITE");
2999
 
    */
3000
3083
}
3001
3084
 
3002
3085
// This callback is called when the invite session state has changed
3014
3097
        _error ("UserAgent: Error: Call is NULL in call state changed callback");
3015
3098
        return;
3016
3099
    } else {
3017
 
        // _debug("    call_on_state_changed: call id %s", call->getCallId().c_str());
3018
 
        // _debug("    call_on_state_changed: call state %s", invitationStateMap[call->getInvSession()->state]);
3019
3100
    }
3020
3101
 
3021
3102
    //Retrieve the body message
3038
3119
        return;
3039
3120
    }
3040
3121
 
 
3122
    /*
 
3123
    pjsip_hdr *allow_header = NULL;
 
3124
    std::string *allowed_options = NULL;
 
3125
 
 
3126
    char header_buffer[500];
 
3127
 
 
3128
    if (e->body.tsx_state.src.rdata->msg_info.msg)
 
3129
        allow_header = (pjsip_hdr *) pjsip_msg_find_hdr (e->body.tsx_state.src.rdata->msg_info.msg, PJSIP_H_ALLOW, NULL);
 
3130
 
 
3131
    if (allow_header) {
 
3132
        allowed_options = new std::string (allow_header->name.ptr, allow_header->name.slen);
 
3133
        allow_header->vptr->print_on (allow_header, header_buffer, 5000);
 
3134
        std::string theHeader (header_buffer);
 
3135
    }
 
3136
 
 
3137
    if (allowed_options)
 
3138
        delete allowed_options;
 
3139
    */
 
3140
 
3041
3141
    // If this is an outgoing INVITE that was created because of
3042
3142
    // REFER/transfer, send NOTIFY to transferer.
3043
3143
    if (call->getXferSub() && e->type==PJSIP_EVENT_TSX_STATE) {
3114
3214
        const pj_str_t * description = pjsip_get_status_text (statusCode);
3115
3215
 
3116
3216
        if (statusCode) {
3117
 
            DBusManager::instance().getCallManager()->sipCallStateChanged (call->getCallId(), std::string (description->ptr, description->slen), statusCode);
 
3217
            // test wether or not dbus manager is instantiated, if not no need to notify the client
 
3218
            if (Manager::instance().getDbusManager())
 
3219
                DBusManager::instance().getCallManager()->sipCallStateChanged (call->getCallId(), std::string (description->ptr, description->slen), statusCode);
3118
3220
        }
3119
3221
    }
3120
3222
 
3137
3239
        accId = Manager::instance().getAccountFromCall (call->getCallId());
3138
3240
        link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accId));
3139
3241
 
3140
 
                // Make sure link is valid
3141
 
        assert(link);
 
3242
        // Make sure link is valid
 
3243
        assert (link);
3142
3244
 
3143
3245
        switch (inv->cause) {
3144
3246
 
3145
 
            // The call terminates normally - BYE / CANCEL
 
3247
                // The call terminates normally - BYE / CANCEL
3146
3248
            case PJSIP_SC_OK:
3147
3249
            case PJSIP_SC_REQUEST_TERMINATED:
3148
3250
                link->SIPCallClosed (call);
3149
3251
                break;
3150
3252
 
3151
3253
            case PJSIP_SC_DECLINE:
3152
 
                _debug("UserAgent: Call %s is declined", call->getCallId().c_str());
3153
 
                                if (inv->role == PJSIP_ROLE_UAC)
3154
 
                                        link->SIPCallServerFailure (call);
3155
 
                                break;
 
3254
                _debug ("UserAgent: Call %s is declined", call->getCallId().c_str());
 
3255
 
 
3256
                if (inv->role == PJSIP_ROLE_UAC)
 
3257
                    link->SIPCallServerFailure (call);
 
3258
 
 
3259
                break;
3156
3260
 
3157
3261
            case PJSIP_SC_NOT_FOUND:            /* peer not found */
3158
3262
            case PJSIP_SC_REQUEST_TIMEOUT:      /* request timeout */
3161
3265
            case PJSIP_SC_UNSUPPORTED_MEDIA_TYPE:
3162
3266
            case PJSIP_SC_UNAUTHORIZED:
3163
3267
            case PJSIP_SC_FORBIDDEN:
3164
 
            case PJSIP_SC_REQUEST_PENDING:
3165
 
            case PJSIP_SC_ADDRESS_INCOMPLETE:
 
3268
            case PJSIP_SC_REQUEST_PENDING:
 
3269
            case PJSIP_SC_ADDRESS_INCOMPLETE:
3166
3270
                link->SIPCallServerFailure (call);
3167
3271
                break;
3168
3272
 
3169
3273
            default:
3170
 
                link->SIPCallServerFailure (call);
 
3274
                link->SIPCallServerFailure (call);
3171
3275
                _error ("UserAgent: Unhandled call state. This is probably a bug.");
3172
3276
                break;
3173
3277
        }
3229
3333
 
3230
3334
    try {
3231
3335
        call->getAudioRtp()->updateDestinationIpAddress();
3232
 
    }
3233
 
    catch(...) {
3234
 
        
 
3336
    } catch (...) {
 
3337
 
3235
3338
    }
3236
3339
 
3237
3340
 
3238
3341
    // Get the crypto attribute containing srtp's cryptographic context (keys, cipher)
3239
3342
    CryptoOffer crypto_offer;
3240
 
    call->getLocalSDP()->get_remote_sdp_crypto_from_offer(remote_sdp, crypto_offer);
 
3343
    call->getLocalSDP()->get_remote_sdp_crypto_from_offer (remote_sdp, crypto_offer);
3241
3344
 
3242
3345
    bool nego_success = false;
3243
 
    if(!crypto_offer.empty()) {
3244
 
 
3245
 
        _debug("UserAgent: Crypto attribute in SDP, init SRTP session");
3246
 
 
3247
 
        // init local cryptografic capabilities for negotiation
3248
 
        std::vector<sfl::CryptoSuiteDefinition>localCapabilities;
3249
 
        for(int i = 0; i < 3; i++) {
3250
 
                localCapabilities.push_back(sfl::CryptoSuites[i]);
3251
 
                }
3252
 
 
3253
 
                sfl::SdesNegotiator sdesnego(localCapabilities, crypto_offer);
3254
 
        
3255
 
                if(sdesnego.negotiate()) {
3256
 
                        _debug("UserAgent: SDES negociation successfull \n");
3257
 
                        nego_success = true;
3258
 
 
3259
 
            _debug("UserAgent: Set remote cryptographic context\n");
 
3346
 
 
3347
    if (!crypto_offer.empty()) {
 
3348
 
 
3349
        _debug ("UserAgent: Crypto attribute in SDP, init SRTP session");
 
3350
 
 
3351
        // init local cryptografic capabilities for negotiation
 
3352
        std::vector<sfl::CryptoSuiteDefinition>localCapabilities;
 
3353
 
 
3354
        for (int i = 0; i < 3; i++) {
 
3355
            localCapabilities.push_back (sfl::CryptoSuites[i]);
 
3356
        }
 
3357
 
 
3358
        // Mkae sure incoming crypto offer is valid
 
3359
        sfl::SdesNegotiator sdesnego (localCapabilities, crypto_offer);
 
3360
 
 
3361
        if (sdesnego.negotiate()) {
 
3362
            _debug ("UserAgent: SDES negociation successfull");
 
3363
            nego_success = true;
 
3364
 
 
3365
            _debug ("UserAgent: Set remote cryptographic context");
 
3366
 
3260
3367
            try {
3261
 
                  call->getAudioRtp()->setRemoteCryptoInfo(sdesnego);
3262
 
            }
3263
 
            catch(...) {}
 
3368
                call->getAudioRtp()->setRemoteCryptoInfo (sdesnego);
 
3369
            } catch (...) {}
3264
3370
 
3265
3371
            DBusManager::instance().getCallManager()->secureSdesOn (call->getCallId());
3266
 
                }
3267
 
                else {
3268
 
                        DBusManager::instance().getCallManager()->secureSdesOff (call->getCallId());
3269
 
                }
 
3372
        } else {
 
3373
            DBusManager::instance().getCallManager()->secureSdesOff (call->getCallId());
 
3374
        }
3270
3375
    }
3271
3376
 
3272
 
    // We did not found any crypto context for this media
3273
 
    if(!nego_success && call->getAudioRtp()->getAudioRtpType() == sfl::Sdes) {
3274
 
       
 
3377
 
 
3378
    // We did not found any crypto context for this media, RTP fallback
 
3379
    if (!nego_success && call->getAudioRtp()->getAudioRtpType() == sfl::Sdes) {
 
3380
 
3275
3381
        // We did not found any crypto context for this media
3276
3382
        // @TODO if SRTPONLY, CallFail
3277
3383
 
3278
 
        _debug("UserAgent: Did not found any crypto or negociation failed but Sdes enabled");
 
3384
        _debug ("UserAgent: Did not found any crypto or negociation failed but Sdes enabled");
3279
3385
        call->getAudioRtp()->stop();
3280
 
        call->getAudioRtp()->setSrtpEnabled(false);
3281
 
 
3282
 
        // if RTPFALLBACK, change RTP session
3283
 
        AccountID accountID = Manager::instance().getAccountFromCall (call->getCallId());
3284
 
        if(Manager::instance().getConfigString (accountID, SRTP_RTP_FALLBACK) == "true")
3285
 
            call->getAudioRtp()->initAudioRtpSession(call);
3286
 
    }
3287
 
 
3288
 
    if(nego_success && call->getAudioRtp()->getAudioRtpType() != sfl::Sdes) {
3289
 
       
3290
 
        // We found a crypto context for this media but Sdes is not 
3291
 
        // enabled for this call, make a try using RTP only...
3292
 
        _debug("UserAgent: SDES not initialized for this call\n");
3293
 
    }
3294
 
 
 
3386
        call->getAudioRtp()->setSrtpEnabled (false);
 
3387
 
 
3388
        // if RTPFALLBACK, change RTP session
 
3389
        AccountID accountID = Manager::instance().getAccountFromCall (call->getCallId());
 
3390
        SIPAccount *account = (SIPAccount *) Manager::instance().getAccount (accountID);
 
3391
 
 
3392
        if (account->getSrtpFallback())
 
3393
            call->getAudioRtp()->initAudioRtpSession (call);
 
3394
    }
 
3395
 
 
3396
    // Start audio rtp session.
3295
3397
 
3296
3398
    Sdp  *sdpSession = call->getLocalSDP();
3297
 
    if(!sdpSession)
3298
 
                return;
 
3399
 
 
3400
    if (!sdpSession)
 
3401
        return;
3299
3402
 
3300
3403
    AudioCodec *sessionMedia = sdpSession->get_session_media();
3301
 
        if(!sessionMedia)
3302
 
                return;
3303
 
 
3304
 
        AudioCodecType pl = (AudioCodecType)sessionMedia->getPayload();
3305
 
        AudioCodec* audiocodec = Manager::instance().getCodecDescriptorMap().instantiateCodec(pl);
3306
 
 
3307
 
        if (audiocodec == NULL)
3308
 
                _error ("UserAgent: No audiocodec found");
 
3404
 
 
3405
    if (!sessionMedia)
 
3406
        return;
 
3407
 
 
3408
    AudioCodecType pl = (AudioCodecType) sessionMedia->getPayload();
 
3409
    AudioCodec* audiocodec = Manager::instance().getCodecDescriptorMap().instantiateCodec (pl);
 
3410
 
 
3411
    if (audiocodec == NULL)
 
3412
        _error ("UserAgent: No audiocodec found");
3309
3413
 
3310
3414
 
3311
3415
    try {
3312
3416
        call->setAudioStart (true);
3313
 
        call->getAudioRtp()->start(audiocodec);
 
3417
        call->getAudioRtp()->start (audiocodec);
3314
3418
    } catch (exception& rtpException) {
3315
3419
        _error ("UserAgent: Error: %s", rtpException.what());
3316
3420
    }
3317
3421
 
3318
3422
}
3319
3423
 
3320
 
void call_on_forked (pjsip_inv_session *inv, pjsip_event *e)
 
3424
void call_on_forked (pjsip_inv_session *inv UNUSED, pjsip_event *e UNUSED)
3321
3425
{
3322
3426
}
3323
3427
 
3324
 
void call_on_tsx_changed (pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
 
3428
void call_on_tsx_changed (pjsip_inv_session *inv UNUSED, pjsip_transaction *tsx, pjsip_event *e)
3325
3429
{
3326
 
        assert(tsx);
3327
 
 
3328
 
    _debug("UserAgent: Transaction changed to state %s", transactionStateMap[tsx->state]);
 
3430
    assert (tsx);
 
3431
 
 
3432
    _debug ("UserAgent: Transaction changed to state %s", transactionStateMap[tsx->state]);
 
3433
 
 
3434
    pjsip_rx_data* r_data;
 
3435
    pjsip_tx_data* t_data;
3329
3436
 
3330
3437
    if (tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING &&
3331
 
            pjsip_method_cmp (&tsx->method, &pjsip_refer_method) ==0) {
 
3438
    pjsip_method_cmp (&tsx->method, &pjsip_refer_method) ==0) {
3332
3439
        /** Handle the refer method **/
3333
3440
        onCallTransfered (inv, e->body.tsx_state.src.rdata);
 
3441
 
3334
3442
    } else if (tsx->role==PJSIP_ROLE_UAS && tsx->state==PJSIP_TSX_STATE_TRYING) {
3335
3443
 
3336
3444
        if (e && e->body.rx_msg.rdata) {
3337
3445
 
3338
3446
 
3339
 
                _debug("Event");
3340
 
            pjsip_tx_data* t_data;
3341
 
            pjsip_rx_data* r_data = e->body.rx_msg.rdata;
 
3447
            _debug ("Event");
 
3448
            r_data = e->body.rx_msg.rdata;
3342
3449
 
3343
3450
            if (r_data && r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD) {
3344
3451
 
3345
 
                _debug("R_data");
 
3452
                _debug ("R_data");
3346
3453
 
3347
3454
                std::string method_info = "INFO";
3348
3455
                std::string method_notify = "NOTIFY";
3349
3456
 
3350
3457
                std::string request =  pjsip_rx_data_get_info (r_data);
3351
3458
 
3352
 
                            _debug("UserAgent: %s", request.c_str());
3353
 
 
3354
 
                            if(request.find (method_notify) != (size_t)-1) {
3355
 
 
3356
 
                            }
3357
 
                                // Must reply 200 OK on SIP INFO request
3358
 
                            else if (request.find (method_info) != (size_t)-1) {
 
3459
                _debug ("UserAgent: %s", request.c_str());
 
3460
 
 
3461
                if (request.find (method_notify) != (size_t)-1) {
 
3462
 
 
3463
                }
 
3464
                // Must reply 200 OK on SIP INFO request
 
3465
                else if (request.find (method_info) != (size_t)-1) {
3359
3466
 
3360
3467
                    pjsip_dlg_create_response (inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data);
3361
3468
 
3363
3470
                }
3364
3471
            }
3365
3472
        }
 
3473
 
 
3474
        // Incoming TEXT message
 
3475
        if (e && e->body.tsx_state.src.rdata) {
 
3476
 
 
3477
            // sender of this message
 
3478
            std::string from;
 
3479
 
 
3480
            // Get the message inside the transaction
 
3481
            r_data = e->body.tsx_state.src.rdata;
 
3482
            std::string formatedMessage = (char*) r_data->msg_info.msg->body->data;
 
3483
 
 
3484
            // Try to determine who is the recipient of the message
 
3485
            SIPCall *call = reinterpret_cast<SIPCall *> (inv->mod_data[getModId() ]);
 
3486
 
 
3487
            if (!call) {
 
3488
                _debug ("Incoming TEXT message: Can't find the recipient of the message");
 
3489
                return;
 
3490
            }
 
3491
 
 
3492
            // Respond with a 200/OK
 
3493
            pjsip_dlg_create_response (inv->dlg, r_data, PJSIP_SC_OK, NULL, &t_data);
 
3494
            pjsip_dlg_send_response (inv->dlg, tsx, t_data);
 
3495
 
 
3496
            std::string message;
 
3497
            std::string urilist;
 
3498
            sfl::InstantMessaging::UriList list;
 
3499
 
 
3500
            sfl::InstantMessaging *module = Manager::instance().getInstantMessageModule();
 
3501
 
 
3502
            try {
 
3503
                // retrive message from formated text
 
3504
                message = module->findTextMessage (formatedMessage);
 
3505
 
 
3506
                // retreive the recipient-list of this message
 
3507
                urilist = module->findTextUriList (formatedMessage);
 
3508
 
 
3509
                // parse the recipient list xml
 
3510
                list = module->parseXmlUriList (urilist);
 
3511
 
 
3512
                // If no item present in the list, peer is considered as the sender
 
3513
                if (list.empty()) {
 
3514
                    from = call->getPeerNumber ();
 
3515
                } else {
 
3516
                    sfl::InstantMessaging::UriEntry entry = list.front();
 
3517
                    sfl::InstantMessaging::UriEntry::iterator iterAttr = entry.find (IM_XML_URI);
 
3518
 
 
3519
                    if (iterAttr->second != "Me")
 
3520
                        from = iterAttr->second;
 
3521
                    else
 
3522
                        from = call->getPeerNumber ();
 
3523
                }
 
3524
 
 
3525
            } catch (sfl::InstantMessageException &e) {
 
3526
                _error ("SipVoipLink: %s", e.what());
 
3527
                message = "";
 
3528
                from = call->getPeerNumber ();
 
3529
            }
 
3530
 
 
3531
 
 
3532
            // strip < and > characters in case of an IP address
 
3533
            std::string stripped;
 
3534
 
 
3535
            if (from[0] == '<' && from[from.size()-1] == '>')
 
3536
                stripped = from.substr (1, from.size()-2);
 
3537
            else
 
3538
                stripped = from;
 
3539
 
 
3540
            // Pass through the instant messaging module if needed
 
3541
            // Right now, it does do anything.
 
3542
            // And notify the clients
 
3543
 
 
3544
            Manager::instance ().incomingMessage (call->getCallId (), stripped, module->receive (message, stripped, call->getCallId ()));
 
3545
        }
 
3546
 
 
3547
 
3366
3548
    }
3367
3549
}
3368
3550
 
3386
3568
        //_debug("Received client registration callback wiht code: %i, %s\n", param->code, descriptionprint.c_str());
3387
3569
        DBusManager::instance().getCallManager()->registrationStateChanged (account->getAccountID(), std::string (description->ptr, description->slen), param->code);
3388
3570
        std::pair<int, std::string> details (param->code, std::string (description->ptr, description->slen));
3389
 
        account->setRegistrationStateDetailed (details);
 
3571
 
 
3572
 
 
3573
        // there a race condition for this ressource when closing the application
 
3574
        if (account)
 
3575
            account->setRegistrationStateDetailed (details);
3390
3576
    }
3391
3577
 
3392
3578
    if (param->status == PJ_SUCCESS) {
3413
3599
                    account->setRegistrationState (ErrorAuth);
3414
3600
                    break;
3415
3601
 
3416
 
                case 423: { // Expiration Interval Too Brief
3417
 
 
3418
 
                    int expire_value;
3419
 
                    std::istringstream stream (account->getRegistrationExpire());
3420
 
                    stream >> expire_value;
3421
 
 
3422
 
                    std::stringstream out;
3423
 
                    out << (expire_value * 2);
3424
 
                    std::string s = out.str(); 
3425
 
 
3426
 
                    Manager::instance().setConfig(account->getAccountID(), CONFIG_ACCOUNT_REGISTRATION_EXPIRE, s);
3427
 
                    account->registerVoIPLink();
3428
 
                }
3429
 
                    break;
 
3602
                case 423: { // Expiration Interval Too Brief
 
3603
 
 
3604
                    int expire_value;
 
3605
                    std::istringstream stream (account->getRegistrationExpire());
 
3606
                    stream >> expire_value;
 
3607
 
 
3608
                    std::stringstream out;
 
3609
                    out << (expire_value * 2);
 
3610
                    std::string s = out.str();
 
3611
 
 
3612
                    account->setRegistrationExpire (s);
 
3613
                    account->registerVoIPLink();
 
3614
                }
 
3615
                break;
3430
3616
 
3431
3617
                default:
3432
3618
                    account->setRegistrationState (Error);
3435
3621
 
3436
3622
            account->setRegister (false);
3437
3623
 
3438
 
            // shutdown this transport since useless
3439
 
            // if(account->getAccountTransport() != _localUDPTransport) {
 
3624
            // shutdown this transport since useless
 
3625
            // if(account->getAccountTransport() != _localUDPTransport) {
3440
3626
 
3441
 
            SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID());
3442
 
            //}
 
3627
            SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID());
 
3628
            //}
3443
3629
 
3444
3630
        } else {
3445
3631
            // Registration/Unregistration is success
3449
3635
                account->setRegistrationState (Unregistered);
3450
3636
                account->setRegister (false);
3451
3637
 
3452
 
                SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID());
 
3638
                SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID());
3453
3639
 
3454
 
                // pjsip_regc_destroy(param->regc);
3455
 
                // account->setRegistrationInfo(NULL);
 
3640
                // pjsip_regc_destroy(param->regc);
 
3641
                // account->setRegistrationInfo(NULL);
3456
3642
            }
3457
3643
        }
3458
3644
    } else {
3459
3645
        account->setRegistrationState (ErrorAuth);
3460
3646
        account->setRegister (false);
3461
3647
 
3462
 
        SIPVoIPLink::instance("")->shutdownSipTransport(account->getAccountID());
 
3648
        SIPVoIPLink::instance ("")->shutdownSipTransport (account->getAccountID());
3463
3649
    }
3464
3650
 
3465
3651
}
3490
3676
    std::string method_name;
3491
3677
    std::string request;
3492
3678
 
3493
 
 
3494
 
    _info("UserAgent: Transaction REQUEST received using transport: %s %s (refcnt=%d)",
3495
 
           rdata->tp_info.transport->obj_name,
3496
 
           rdata->tp_info.transport->info,
3497
 
           (int)pj_atomic_get(rdata->tp_info.transport->ref_cnt));
 
3679
    _info ("UserAgent: Transaction REQUEST received using transport: %s %s (refcnt=%d)",
 
3680
    rdata->tp_info.transport->obj_name,
 
3681
    rdata->tp_info.transport->info,
 
3682
    (int) pj_atomic_get (rdata->tp_info.transport->ref_cnt));
3498
3683
 
3499
3684
    // No need to go any further on incoming ACK
3500
 
    if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg(rdata) != NULL) {
3501
 
        _info("UserAgent: received an ACK");
 
3685
    if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg (rdata) != NULL) {
 
3686
        _info ("UserAgent: received an ACK");
3502
3687
        return true;
3503
3688
    }
3504
3689
 
3514
3699
    // Get the account id of callee from username and server
3515
3700
    account_id = Manager::instance().getAccountIdFromNameAndServer (userName, server);
3516
3701
 
 
3702
    _debug ("UserAgent: Account ID for this call, %s", account_id.c_str());
 
3703
 
3517
3704
    /* If we don't find any account to receive the call */
3518
3705
    if (account_id == AccountNULL) {
3519
3706
        _debug ("UserAgent: Username %s doesn't match any account, using IP2IP!",userName.c_str());
3525
3712
 
3526
3713
    /* If we can't find any voIP link to handle the incoming call */
3527
3714
    if (!link) {
3528
 
        _warn("UserAgent: Error: cannot retrieve the voiplink from the account ID...");
3529
 
        pj_strdup2 (_pool, &reason, "ERROR: cannot retrieve the voip link from account");
3530
 
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, 
3531
 
                                       &reason, NULL, NULL);
 
3715
        _warn ("UserAgent: Error: cannot retrieve the voiplink from the account ID...");
 
3716
        pj_strdup2 (_pool, &reason, "ERROR: cannot retrieve the voip link from account");
 
3717
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR,
 
3718
        &reason, NULL, NULL);
3532
3719
        return true;
3533
3720
        return false;
3534
3721
    }
3535
3722
 
3536
3723
    // Parse the display name from "From" header
3537
3724
    char* from_header = strstr (rdata->msg_info.msg_buf, "From: ");
 
3725
 
3538
3726
    if (from_header) {
3539
3727
        std::string temp (from_header);
3540
3728
        int begin_displayName = temp.find ("\"") + 1;
3541
3729
        int end_displayName = temp.rfind ("\"");
3542
3730
        displayName = temp.substr (begin_displayName, end_displayName - begin_displayName);
3543
 
        if(displayName.size() > 25) {
3544
 
            displayName = std::string ("");
3545
 
        }
 
3731
 
 
3732
        if (displayName.size() > 25) {
 
3733
            displayName = std::string ("");
 
3734
        }
3546
3735
    } else {
3547
3736
        displayName = std::string ("");
3548
3737
    }
3558
3747
    // Store the peer number
3559
3748
    char tmp[PJSIP_MAX_URL_SIZE];
3560
3749
    int length = pjsip_uri_print (PJSIP_URI_IN_FROMTO_HDR,
3561
 
                                  sip_uri, tmp, PJSIP_MAX_URL_SIZE);
 
3750
    sip_uri, tmp, PJSIP_MAX_URL_SIZE);
3562
3751
 
3563
3752
    std::string peerNumber (tmp, length);
3564
3753
 
3565
3754
    //Remove sip: prefix
3566
 
    size_t found = peerNumber.find("sip:");
3567
 
    if (found!=std::string::npos)
3568
 
        peerNumber.erase(found, found+4);
3569
 
 
3570
 
    found = peerNumber.find("@");
3571
 
    if (found!=std::string::npos)
3572
 
        peerNumber.erase(found);
3573
 
 
3574
 
    _debug("UserAgent: Peer number: %s", peerNumber.c_str());
 
3755
    size_t found = peerNumber.find ("sip:");
 
3756
 
 
3757
    if (found!=std::string::npos)
 
3758
        peerNumber.erase (found, found+4);
 
3759
 
 
3760
    found = peerNumber.find ("@");
 
3761
 
 
3762
    if (found!=std::string::npos)
 
3763
        peerNumber.erase (found);
 
3764
 
 
3765
    _debug ("UserAgent: Peer number: %s", peerNumber.c_str());
3575
3766
 
3576
3767
    // Get the server voicemail notification
3577
3768
    // Catch the NOTIFY message
3603
3794
    if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) {
3604
3795
        if (rdata->msg_info.msg->line.req.method.id != PJSIP_ACK_METHOD) {
3605
3796
            pj_strdup2 (_pool, &reason, "user agent unable to handle this request ");
3606
 
            pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, 
3607
 
                                           &reason, NULL, NULL);
 
3797
            pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED,
 
3798
            &reason, NULL, NULL);
3608
3799
            return true;
3609
3800
        }
3610
3801
    }
3612
3803
    account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id));
3613
3804
 
3614
3805
    get_remote_sdp_from_offer (rdata, &r_sdp);
3615
 
    if(account->getActiveCodecs().empty()) {
3616
 
        _warn ("UserAgent: Error: No active codec");
3617
 
        pj_strdup2 (_pool, &reason, "no active codec");
3618
 
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE , 
3619
 
                                                                      &reason, NULL, NULL);
 
3806
 
 
3807
    if (account->getActiveCodecs().empty()) {
 
3808
        _warn ("UserAgent: Error: No active codec");
 
3809
        pj_strdup2 (_pool, &reason, "no active codec");
 
3810
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE ,
 
3811
        &reason, NULL, NULL);
3620
3812
        return true;
3621
3813
    }
3622
3814
 
3623
3815
    // Verify that we can handle the request
3624
3816
    status = pjsip_inv_verify_request (rdata, &options, NULL, NULL, _endpt, NULL);
 
3817
 
3625
3818
    if (status != PJ_SUCCESS) {
3626
3819
        pj_strdup2 (_pool, &reason, "user agent unable to handle this INVITE");
3627
 
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, 
3628
 
                                       &reason, NULL, NULL);
 
3820
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_METHOD_NOT_ALLOWED,
 
3821
        &reason, NULL, NULL);
3629
3822
        return true;
3630
3823
    }
3631
3824
 
3632
3825
    /******************************************* URL HOOK *********************************************/
3633
3826
 
3634
 
    if (Manager::instance().getConfigString (HOOKS, URLHOOK_SIP_ENABLED) == "1") {
 
3827
    if (Manager::instance().hookPreference.getSipEnabled()) {
3635
3828
 
3636
 
        _debug("UserAgent: Set sip url hooks");
 
3829
        _debug ("UserAgent: Set sip url hooks");
3637
3830
 
3638
3831
        std::string header_value;
3639
3832
 
3640
 
        header_value = fetch_header_value (rdata->msg_info.msg, Manager::instance().getConfigString (HOOKS, URLHOOK_SIP_FIELD));
 
3833
        header_value = fetch_header_value (rdata->msg_info.msg,
 
3834
        Manager::instance().hookPreference.getUrlSipField());
3641
3835
 
3642
3836
        if (header_value.size () < header_value.max_size()) {
3643
3837
            if (header_value!="") {
3644
3838
                urlhook->addAction (header_value,
3645
 
                                    Manager::instance().getConfigString (HOOKS, URLHOOK_COMMAND));
 
3839
                Manager::instance().hookPreference.getUrlCommand());
3646
3840
            }
3647
3841
        } else
3648
3842
            throw length_error ("UserAgent: Url exceeds std::string max_size");
3660
3854
 
3661
3855
    // If an error occured at the call creation
3662
3856
    if (!call) {
3663
 
        _warn("UserAgent: Error: Unable to create an incoming call");
 
3857
        _warn ("UserAgent: Error: Unable to create an incoming call");
3664
3858
        pj_strdup2 (_pool, &reason, "unable to create an incoming call");
3665
 
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, 
3666
 
                                       &reason, NULL, NULL);
 
3859
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR,
 
3860
        &reason, NULL, NULL);
3667
3861
        return false;
3668
3862
    }
3669
3863
 
 
3864
    Manager::instance().associateCallToAccount (call->getCallId(), account_id);
 
3865
 
 
3866
 
3670
3867
    std::string addrToUse, addrSdp ="0.0.0.0";
3671
3868
 
3672
3869
    pjsip_tpselector *tp;
3675
3872
 
3676
3873
        // May use the published address as well
3677
3874
 
3678
 
        addrToUse = SIPVoIPLink::instance("")->getInterfaceAddrFromName(account->getLocalInterface ());
 
3875
        addrToUse = SIPVoIPLink::instance ("")->getInterfaceAddrFromName (account->getLocalInterface ());
3679
3876
        account->isStunEnabled () ? addrSdp = account->getPublishedAddress () : addrSdp = addrToUse;
3680
3877
        // Set the appropriate transport to have the right VIA header
3681
3878
        link->init_transport_selector (account->getAccountTransport (), &tp);
3682
3879
 
3683
 
        if(account->getAccountTransport()) {
 
3880
        if (account->getAccountTransport()) {
3684
3881
 
3685
 
                _debug("UserAgent: SIP transport for this account: %s %s (refcnt=%i)",
3686
 
                account->getAccountTransport()->obj_name,
3687
 
                account->getAccountTransport()->info,
3688
 
                (int)pj_atomic_get(account->getAccountTransport()->ref_cnt));
 
3882
            _debug ("UserAgent: SIP transport for this account: %s %s (refcnt=%i)",
 
3883
            account->getAccountTransport()->obj_name,
 
3884
            account->getAccountTransport()->info,
 
3885
            (int) pj_atomic_get (account->getAccountTransport()->ref_cnt));
3689
3886
        }
3690
3887
 
3691
3888
    }
3701
3898
    call->setConnectionState (Call::Progressing);
3702
3899
    call->setPeerNumber (peerNumber);
3703
3900
    call->setDisplayName (displayName);
3704
 
    call->initRecFileName();
 
3901
    call->initRecFileName (peerNumber);
3705
3902
 
3706
 
    _debug("UserAgent: DisplayName: %s", displayName.c_str());
 
3903
    _debug ("UserAgent: DisplayName: %s", displayName.c_str());
3707
3904
 
3708
3905
 
3709
3906
    // Have to do some stuff with the SDP
3713
3910
    // We retrieve the remote sdp offer in the rdata struct to begin the negociation
3714
3911
    call->getLocalSDP()->set_ip_address (addrSdp);
3715
3912
 
 
3913
    // Init audio rtp session
3716
3914
    try {
 
3915
        _debug ("UserAgent: Create RTP session for this call");
3717
3916
        call->getAudioRtp()->initAudioRtpConfig (call);
3718
3917
        call->getAudioRtp()->initAudioRtpSession (call);
3719
3918
    } catch (...) {
3720
3919
        _warn ("UserAgent: Error: Failed to create rtp thread from answer");
3721
3920
    }
3722
3921
 
 
3922
    // Retreive crypto offer from body, if any
 
3923
    if (rdata->msg_info.msg->body) {
 
3924
 
 
3925
        char sdpbuffer[1000];
 
3926
        rdata->msg_info.msg->body->print_body (rdata->msg_info.msg->body, sdpbuffer, 1000);
 
3927
        std::string sdpoffer = std::string (sdpbuffer);
 
3928
        size_t start = sdpoffer.find ("a=crypto:");
 
3929
 
 
3930
        // Found crypto header in SDP
 
3931
        if (start != std::string::npos) {
 
3932
 
 
3933
            std::string cryptoHeader = sdpoffer.substr (start, (sdpoffer.size() - start) -1);
 
3934
            _debug ("UserAgent: Found incoming crypto offer: %s", cryptoHeader.c_str());
 
3935
 
 
3936
            CryptoOffer crypto_offer;
 
3937
            crypto_offer.push_back (cryptoHeader);
 
3938
 
 
3939
            bool nego_success = false;
 
3940
 
 
3941
            if (!crypto_offer.empty()) {
 
3942
 
 
3943
                _debug ("UserAgent: Crypto attribute in SDP, init SRTP session");
 
3944
 
 
3945
                // init local cryptografic capabilities for negotiation
 
3946
                std::vector<sfl::CryptoSuiteDefinition>localCapabilities;
 
3947
 
 
3948
                for (int i = 0; i < 3; i++) {
 
3949
                    localCapabilities.push_back (sfl::CryptoSuites[i]);
 
3950
                }
 
3951
 
 
3952
                sfl::SdesNegotiator sdesnego (localCapabilities, crypto_offer);
 
3953
 
 
3954
                if (sdesnego.negotiate()) {
 
3955
                    _debug ("UserAgent: SDES negociation successfull \n");
 
3956
                    nego_success = true;
 
3957
 
 
3958
                    try {
 
3959
                        _debug ("UserAgent: Create RTP session for this call");
 
3960
                        call->getAudioRtp()->setRemoteCryptoInfo (sdesnego);
 
3961
                        call->getAudioRtp()->initLocalCryptoInfo (call);
 
3962
                    } catch (...) {
 
3963
                        _warn ("UserAgent: Error: Failed to create rtp thread from answer");
 
3964
                    }
 
3965
                }
 
3966
            }
 
3967
        }
 
3968
    }
 
3969
 
 
3970
 
3723
3971
    status = call->getLocalSDP()->receiving_initial_offer (r_sdp, account->getActiveCodecs ());
3724
3972
 
3725
3973
    if (status!=PJ_SUCCESS) {
3726
 
        delete call; call = NULL;
3727
 
        _warn("UserAgent: fail in receiving initial offer");
 
3974
        delete call;
 
3975
        call = NULL;
 
3976
        _warn ("UserAgent: fail in receiving initial offer");
3728
3977
        pj_strdup2 (_pool, &reason, "fail in receiving initial offer");
3729
 
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, 
3730
 
                                       &reason, NULL, NULL);
 
3978
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR,
 
3979
        &reason, NULL, NULL);
3731
3980
        return false;
3732
3981
    }
3733
3982
 
3734
3983
    /* Create the local dialog (UAS) */
3735
3984
    status = pjsip_dlg_create_uas (pjsip_ua_instance(), rdata, NULL, &dialog);
 
3985
 
3736
3986
    if (status != PJ_SUCCESS) {
3737
 
        delete call; call = NULL;
3738
 
        _warn("UserAgent: Error: Failed to create uas dialog");
 
3987
        delete call;
 
3988
        call = NULL;
 
3989
        _warn ("UserAgent: Error: Failed to create uas dialog");
3739
3990
        pj_strdup2 (_pool, &reason, "fail to create uas dialog");
3740
 
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, 
3741
 
                                       &reason, NULL, NULL);
 
3991
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR,
 
3992
        &reason, NULL, NULL);
3742
3993
        return false;
3743
3994
    }
3744
3995
 
3767
4018
    call->setConnectionState (Call::Ringing);
3768
4019
 
3769
4020
    _debug ("UserAgent: Add call to account link");
 
4021
 
3770
4022
    if (Manager::instance().incomingCall (call, account_id)) {
3771
 
        // Add this call to the callAccountMap in ManagerImpl
3772
 
        Manager::instance().getAccountLink (account_id)->addCall (call);
3773
 
        } else {
3774
 
                // Fail to notify UI
3775
 
                delete call; call = NULL;
3776
 
                _warn ("UserAgent: Fail to notify UI!");
3777
 
                pj_strdup2 (_pool, &reason, "fail to notify ui");
3778
 
                pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR,
3779
 
                                &reason, NULL, NULL);
3780
 
                return false;
3781
 
        }
 
4023
        // Add this call to the callAccountMap in ManagerImpl
 
4024
        Manager::instance().getAccountLink (account_id)->addCall (call);
 
4025
    } else {
 
4026
        // Fail to notify UI
 
4027
        delete call;
 
4028
        call = NULL;
 
4029
        _warn ("UserAgent: Fail to notify UI!");
 
4030
        pj_strdup2 (_pool, &reason, "fail to notify ui");
 
4031
        pjsip_endpt_respond_stateless (_endpt, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR,
 
4032
        &reason, NULL, NULL);
 
4033
        return false;
 
4034
    }
3782
4035
 
3783
4036
    /* Done */
3784
4037
    return true;
3788
4041
pj_bool_t mod_on_rx_response (pjsip_rx_data *rdata)
3789
4042
{
3790
4043
    _info ("UserAgent: Transaction response using transport: %s %s (refcnt=%d)",
3791
 
           rdata->tp_info.transport->obj_name,
3792
 
           rdata->tp_info.transport->info,
3793
 
           (int)pj_atomic_get(rdata->tp_info.transport->ref_cnt));
 
4044
    rdata->tp_info.transport->obj_name,
 
4045
    rdata->tp_info.transport->info,
 
4046
    (int) pj_atomic_get (rdata->tp_info.transport->ref_cnt));
3794
4047
 
3795
4048
    pjsip_dialog *dlg;
3796
 
    dlg = pjsip_rdata_get_dlg( rdata );
3797
 
 
3798
 
        if(dlg != NULL) {
3799
 
                pjsip_transaction *tsx = pjsip_rdata_get_tsx( rdata );
3800
 
                if ( tsx != NULL && tsx->method.id == PJSIP_INVITE_METHOD) {
3801
 
                        if (tsx->status_code < 200) {
3802
 
                                _info("UserAgent: Received provisional response");
3803
 
                        }
3804
 
                        else if (tsx->status_code >= 300) {
3805
 
                            _warn("UserAgent: Dialog failed");
3806
 
                                // pjsip_dlg_dec_session(dlg);
3807
 
                                // ACK for non-2xx final response is sent by transaction.
3808
 
                        }
3809
 
                        else {
3810
 
                                _info("UserAgent: Received 200 OK response");
3811
 
                                sendAck(dlg, rdata);
3812
 
                        }
3813
 
                }
3814
 
        }
 
4049
    dlg = pjsip_rdata_get_dlg (rdata);
 
4050
 
 
4051
    if (dlg != NULL) {
 
4052
        pjsip_transaction *tsx = pjsip_rdata_get_tsx (rdata);
 
4053
 
 
4054
        if (tsx != NULL && tsx->method.id == PJSIP_INVITE_METHOD) {
 
4055
            if (tsx->status_code < 200) {
 
4056
                _info ("UserAgent: Received provisional response");
 
4057
            } else if (tsx->status_code >= 300) {
 
4058
                _warn ("UserAgent: Dialog failed");
 
4059
                // pjsip_dlg_dec_session(dlg);
 
4060
                // ACK for non-2xx final response is sent by transaction.
 
4061
            } else {
 
4062
                _info ("UserAgent: Received 200 OK response");
 
4063
                sendAck (dlg, rdata);
 
4064
            }
 
4065
        }
 
4066
    }
3815
4067
 
3816
4068
    return PJ_SUCCESS;
3817
4069
}
3818
4070
 
3819
 
static void sendAck(pjsip_dialog *dlg, pjsip_rx_data *rdata) {
3820
 
 
3821
 
        pjsip_tx_data *tdata;
3822
 
 
3823
 
        // Create ACK request
3824
 
        pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata);
3825
 
 
3826
 
        pjsip_dlg_send_request( dlg, tdata,-1, NULL);
 
4071
static void sendAck (pjsip_dialog *dlg, pjsip_rx_data *rdata)
 
4072
{
 
4073
 
 
4074
    pjsip_tx_data *tdata;
 
4075
 
 
4076
    // Create ACK request
 
4077
    pjsip_dlg_create_request (dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata);
 
4078
 
 
4079
    pjsip_dlg_send_request (dlg, tdata,-1, NULL);
3827
4080
}
3828
4081
 
3829
4082
void onCallTransfered (pjsip_inv_session *inv, pjsip_rx_data *rdata)
3848
4101
 
3849
4102
    /* Find the Refer-To header */
3850
4103
    refer_to = (pjsip_generic_string_hdr*)
3851
 
               pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_refer_to, NULL);
 
4104
    pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_refer_to, NULL);
3852
4105
 
3853
4106
    if (refer_to == NULL) {
3854
4107
        /* Invalid Request.
3861
4114
 
3862
4115
    /* Find optional Refer-Sub header */
3863
4116
    refer_sub = (pjsip_generic_string_hdr*)
3864
 
                pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_refer_sub, NULL);
 
4117
    pjsip_msg_find_hdr_by_name (rdata->msg_info.msg, &str_refer_sub, NULL);
3865
4118
 
3866
4119
    if (refer_sub) {
3867
4120
        if (!pj_strnicmp2 (&refer_sub->hvalue, "true", 4) ==0)
3878
4131
    code = PJSIP_SC_ACCEPTED;
3879
4132
 
3880
4133
    _debug ("UserAgent: Call to %.*s is being transfered to %.*s",
3881
 
            (int) inv->dlg->remote.info_str.slen,
3882
 
            inv->dlg->remote.info_str.ptr,
3883
 
            (int) refer_to->hvalue.slen,
3884
 
            refer_to->hvalue.ptr);
 
4134
    (int) inv->dlg->remote.info_str.slen,
 
4135
    inv->dlg->remote.info_str.ptr,
 
4136
    (int) refer_to->hvalue.slen,
 
4137
    refer_to->hvalue.ptr);
3885
4138
 
3886
4139
    if (no_refer_sub) {
3887
4140
        /*
3892
4145
        pjsip_hdr *hdr;
3893
4146
 
3894
4147
        status = pjsip_dlg_create_response (inv->dlg, rdata, code, NULL,
3895
 
                                            &tdata);
 
4148
        &tdata);
3896
4149
 
3897
4150
        if (status != PJ_SUCCESS) {
3898
4151
            _debug ("UserAgent: Unable to create 2xx response to REFER -- %d", status);
3901
4154
 
3902
4155
        /* Add Refer-Sub header */
3903
4156
        hdr = (pjsip_hdr*)
3904
 
              pjsip_generic_string_hdr_create (tdata->pool, &str_refer_sub,
3905
 
                                               &str_false);
 
4157
        pjsip_generic_string_hdr_create (tdata->pool, &str_refer_sub,
 
4158
        &str_false);
3906
4159
 
3907
4160
        pjsip_msg_add_hdr (tdata->msg, hdr);
3908
4161
 
3909
4162
 
3910
4163
        /* Send answer */
3911
4164
        status = pjsip_dlg_send_response (inv->dlg, pjsip_rdata_get_tsx (rdata),
3912
 
                                          tdata);
 
4165
        tdata);
3913
4166
 
3914
4167
        if (status != PJ_SUCCESS) {
3915
4168
            _debug ("UserAgent: Unable to create 2xx response to REFER -- %d", status);
3948
4201
            pjsip_hdr *hdr;
3949
4202
 
3950
4203
            hdr = (pjsip_hdr*)
3951
 
                  pjsip_generic_string_hdr_create (inv->dlg->pool,
3952
 
                                                   &str_refer_sub,
3953
 
                                                   &str_true);
 
4204
            pjsip_generic_string_hdr_create (inv->dlg->pool,
 
4205
            &str_refer_sub,
 
4206
            &str_true);
3954
4207
            pj_list_push_back (&hdr_list, hdr);
3955
4208
 
3956
4209
        }
3960
4213
 
3961
4214
        /* Create initial NOTIFY request */
3962
4215
        status = pjsip_xfer_notify (sub, PJSIP_EVSUB_STATE_ACTIVE,
3963
 
                                    100, NULL, &tdata);
 
4216
        100, NULL, &tdata);
3964
4217
 
3965
4218
        if (status != PJ_SUCCESS) {
3966
4219
            _debug ("UserAgent: Unable to create NOTIFY to REFER -- %d", status);
4002
4255
        /* Notify xferer about the error (if we have subscription) */
4003
4256
        if (sub) {
4004
4257
            status = pjsip_xfer_notify (sub, PJSIP_EVSUB_STATE_TERMINATED,
4005
 
                                        500, NULL, &tdata);
 
4258
            500, NULL, &tdata);
4006
4259
 
4007
4260
            if (status != PJ_SUCCESS) {
4008
4261
                _debug ("UserAgent: Unable to create NOTIFY to REFER -- %d", status);
4042
4295
 
4043
4296
        /* Put the invite_data in the subscription. */
4044
4297
        pjsip_evsub_set_mod_data (sub, _mod_ua.id,
4045
 
                                  newCall);
 
4298
        newCall);
4046
4299
    }
4047
4300
}
4048
4301
 
4068
4321
     * On incoming NOTIFY, notify application about call transfer progress.
4069
4322
     */
4070
4323
    else if (pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_ACTIVE ||
4071
 
             pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_TERMINATED) {
 
4324
    pjsip_evsub_get_state (sub) == PJSIP_EVSUB_STATE_TERMINATED) {
4072
4325
 
4073
4326
        pjsip_msg *msg;
4074
4327
        pjsip_msg_body *body;
4104
4357
 
4105
4358
        /* This better be a NOTIFY request */
4106
4359
        if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD &&
4107
 
                 request.find(method_notify) != (size_t)-1) {
 
4360
        request.find (method_notify) != (size_t)-1) {
4108
4361
 
4109
4362
            /* Check if there's body */
4110
4363
            msg = r_data->msg_info.msg;
4117
4370
 
4118
4371
            /* Check for appropriate content */
4119
4372
            if (pj_stricmp2 (&body->content_type.type, "message") != 0 ||
4120
 
                    pj_stricmp2 (&body->content_type.subtype, "sipfrag") != 0) {
 
4373
            pj_stricmp2 (&body->content_type.subtype, "sipfrag") != 0) {
4121
4374
                _warn ("UserAgent: Warning! Received NOTIFY without message/sipfrag content");
4122
4375
                return;
4123
4376
            }
4137
4390
        }
4138
4391
 
4139
4392
        // Get call coresponding to this transaction
4140
 
        std::string transferID(r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen);
4141
 
        std::map<std::string, CallID>::iterator it = transferCallID.find(transferID);
 
4393
        std::string transferID (r_data->msg_info.cid->id.ptr, r_data->msg_info.cid->id.slen);
 
4394
        std::map<std::string, CallID>::iterator it = transferCallID.find (transferID);
4142
4395
        CallID cid = it->second;
4143
4396
        SIPCall *call = dynamic_cast<SIPCall *> (link->getCall (cid));
4144
4397
 
4153
4406
 
4154
4407
        cont = !is_last;
4155
4408
 
4156
 
                _debug("UserAgent: Notification status line: %d", status_line.code);
 
4409
        _debug ("UserAgent: Notification status line: %d", status_line.code);
 
4410
 
4157
4411
        if (status_line.code/100 == 2) {
4158
4412
 
4159
 
                _debug ("UserAgent: Received 200 OK on call transfered, stop call!");
 
4413
            _debug ("UserAgent: Received 200 OK on call transfered, stop call!");
4160
4414
            pjsip_tx_data *tdata;
4161
4415
 
4162
4416
            status = pjsip_inv_end_session (call->getInvSession(), PJSIP_SC_GONE, NULL, &tdata);
4211
4465
    }
4212
4466
}
4213
4467
 
4214
 
void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
 
4468
void on_rx_offer (pjsip_inv_session *inv, const pjmedia_sdp_session *offer UNUSED)
4215
4469
{
4216
 
        _info("UserAgent: Received SDP offer");
 
4470
    _info ("UserAgent: Received SDP offer");
4217
4471
 
4218
4472
 
4219
4473
#ifdef CAN_REINVITE
4244
4498
 
4245
4499
}
4246
4500
 
4247
 
void on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
 
4501
void on_create_offer (pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
4248
4502
{
4249
 
        _info("UserAgent: Create new SDP offer");
4250
 
 
4251
 
         /* Retrieve the call information */
4252
 
        SIPCall * call = NULL;
4253
 
        call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]);
4254
 
 
4255
 
        CallID callid = call->getCallId();
4256
 
        AccountID accountid = Manager::instance().getAccountFromCall(callid);
4257
 
 
4258
 
    SIPAccount *account = dynamic_cast<SIPAccount *>(Manager::instance().getAccount(accountid));
 
4503
    _info ("UserAgent: Create new SDP offer");
 
4504
 
 
4505
    /* Retrieve the call information */
 
4506
    SIPCall * call = NULL;
 
4507
    call = reinterpret_cast<SIPCall*> (inv->mod_data[_mod_ua.id]);
 
4508
 
 
4509
    CallID callid = call->getCallId();
 
4510
    AccountID accountid = Manager::instance().getAccountFromCall (callid);
 
4511
 
 
4512
    SIPAccount *account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (accountid));
4259
4513
 
4260
4514
    SIPVoIPLink *link = dynamic_cast<SIPVoIPLink *> (Manager::instance().getAccountLink (accountid));
4261
4515
 
4262
 
        // Set the local address
4263
 
        std::string localAddress = link->getInterfaceAddrFromName(account->getLocalInterface ());
4264
 
        // Set SDP parameters - Set to local
4265
 
        std::string addrSdp = localAddress;
4266
 
 
4267
 
        _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str());
4268
 
 
4269
 
        // If local address bound to ANY, reslove it using PJSIP
4270
 
        if (localAddress == "0.0.0.0") {
4271
 
                link->loadSIPLocalIP (&localAddress);
4272
 
        }
4273
 
 
4274
 
        // Local address to appear in SDP
4275
 
        if (addrSdp == "0.0.0.0") {
4276
 
                addrSdp = localAddress;
4277
 
        }
 
4516
    // Set the local address
 
4517
    std::string localAddress = link->getInterfaceAddrFromName (account->getLocalInterface ());
 
4518
    // Set SDP parameters - Set to local
 
4519
    std::string addrSdp = localAddress;
 
4520
 
 
4521
    _debug ("UserAgent: Local Address for IP2IP call: %s", localAddress.c_str());
 
4522
 
 
4523
    // If local address bound to ANY, reslove it using PJSIP
 
4524
    if (localAddress == "0.0.0.0") {
 
4525
        link->loadSIPLocalIP (&localAddress);
 
4526
    }
 
4527
 
 
4528
    // Local address to appear in SDP
 
4529
    if (addrSdp == "0.0.0.0") {
 
4530
        addrSdp = localAddress;
 
4531
    }
4278
4532
 
4279
4533
    // Set local address for RTP media
4280
4534
    setCallAudioLocal (call, localAddress);
4281
4535
 
4282
4536
    // Building the local SDP offer
4283
4537
    call->getLocalSDP()->set_ip_address (addrSdp);
4284
 
    call->getLocalSDP()->create_initial_offer( account->getActiveCodecs() );
 
4538
    call->getLocalSDP()->create_initial_offer (account->getActiveCodecs());
4285
4539
 
4286
4540
    *p_offer = call->getLocalSDP()->get_local_sdp_session();
4287
4541
 
4337
4591
 
4338
4592
    status = pjsip_endpt_send_response (_endpt, &res_addr, tdata, NULL, NULL);
4339
4593
 
4340
 
    
 
4594
 
4341
4595
    if (status != PJ_SUCCESS)
4342
4596
        pjsip_tx_data_dec_ref (tdata);
4343
4597
}
4349
4603
{
4350
4604
    SIPAccount *account = NULL;
4351
4605
 
 
4606
    _debug ("UserAgent: Set local media information for this call");
 
4607
 
4352
4608
    if (call) {
4353
 
        account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (Manager::instance().getAccountFromCall (call->getCallId ())));
 
4609
 
 
4610
        AccountID account_id = Manager::instance().getAccountFromCall (call->getCallId ());
 
4611
 
 
4612
        account = dynamic_cast<SIPAccount *> (Manager::instance().getAccount (account_id));
 
4613
 
 
4614
 
4354
4615
 
4355
4616
        // Setting Audio
4356
4617
        unsigned int callLocalAudioPort = RANDOM_LOCAL_PORT;
4362
4623
            //localIP = account->getPublishedAddress ();
4363
4624
        }
4364
4625
 
4365
 
        _debug ("            Setting local ip address: %s", localIP.c_str());
4366
 
 
4367
 
        _debug ("            Setting local audio port to: %d", callLocalAudioPort);
4368
 
        _debug ("            Setting local audio port (external) to: %d", callLocalExternAudioPort);
 
4626
        _debug ("UserAgent: Setting local ip address: %s", localIP.c_str());
 
4627
        _debug ("UserAgent: Setting local audio port to: %d", callLocalAudioPort);
 
4628
        _debug ("UserAgent: Setting local audio port (external) to: %d", callLocalExternAudioPort);
4369
4629
 
4370
4630
        // Set local audio port for SIPCall(id)
4371
4631
        call->setLocalIp (localIP);
4375
4635
        call->getLocalSDP()->attribute_port_to_all_media (callLocalExternAudioPort);
4376
4636
 
4377
4637
        return true;
 
4638
    } else {
 
4639
 
 
4640
        _error ("UserAgent: Error: No call found while setting media information for this call");
 
4641
 
 
4642
        return false;
 
4643
 
4378
4644
    }
4379
 
 
4380
 
    return false;
4381
4645
}
4382
4646
 
4383
4647
std::string fetch_header_value (pjsip_msg *msg, std::string field)
4440
4704
}
4441
4705
 
4442
4706
 
4443
 
int get_iface_list(struct ifconf *ifconf)
 
4707
int get_iface_list (struct ifconf *ifconf)
4444
4708
{
4445
 
   int sock, rval;
4446
 
 
4447
 
   if((sock = socket(AF_INET,SOCK_STREAM,0)) < 0)
4448
 
       _debug("get_iface_list error could not open socket\n");
4449
 
 
4450
 
 
4451
 
   if((rval = ioctl(sock, SIOCGIFCONF , (char*) ifconf  )) < 0 )
4452
 
       _debug("get_iface_list error ioctl(SIOGIFCONF)\n");
4453
 
 
4454
 
   close(sock);
4455
 
 
4456
 
   return rval;
 
4709
    int sock, rval;
 
4710
 
 
4711
    if ( (sock = socket (AF_INET,SOCK_STREAM,0)) < 0)
 
4712
        _debug ("get_iface_list error could not open socket\n");
 
4713
 
 
4714
 
 
4715
    if ( (rval = ioctl (sock, SIOCGIFCONF , (char*) ifconf)) < 0)
 
4716
        _debug ("get_iface_list error ioctl(SIOGIFCONF)\n");
 
4717
 
 
4718
    close (sock);
 
4719
 
 
4720
    return rval;
4457
4721
}
4458
4722
 
4459
4723
 
4460
 
std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName(void)
 
4724
std::vector<std::string> SIPVoIPLink::getAllIpInterfaceByName (void)
4461
4725
{
4462
4726
    std::vector<std::string> ifaceList;
4463
4727
 
4465
4729
    struct ifconf ifconf;
4466
4730
    int  nifaces;
4467
4731
 
4468
 
    // add the default 
4469
 
    ifaceList.push_back(std::string("default"));
 
4732
    // add the default
 
4733
    ifaceList.push_back (std::string ("default"));
4470
4734
 
4471
 
    memset(&ifconf,0,sizeof(ifconf));
 
4735
    memset (&ifconf,0,sizeof (ifconf));
4472
4736
    ifconf.ifc_buf = (char*) (ifreqs);
4473
 
    ifconf.ifc_len = sizeof(ifreqs);
4474
 
 
4475
 
    if(get_iface_list(&ifconf) < 0)
4476
 
        _debug("getAllIpInterfaceByName error could not get interface list\n");
4477
 
 
4478
 
    nifaces =  ifconf.ifc_len/sizeof(struct ifreq);
4479
 
 
4480
 
    _debug("Interfaces (count = %d):\n", nifaces);
4481
 
    for(int i = 0; i < nifaces; i++) {
4482
 
        _debug("  %s  ", ifreqs[i].ifr_name);
4483
 
        ifaceList.push_back(std::string (ifreqs[i].ifr_name));
4484
 
        printf("    %s\n", getInterfaceAddrFromName(std::string (ifreqs[i].ifr_name)).c_str());
 
4737
    ifconf.ifc_len = sizeof (ifreqs);
 
4738
 
 
4739
    if (get_iface_list (&ifconf) < 0)
 
4740
        _debug ("getAllIpInterfaceByName error could not get interface list\n");
 
4741
 
 
4742
    nifaces =  ifconf.ifc_len/sizeof (struct ifreq);
 
4743
 
 
4744
    _debug ("Interfaces (count = %d):\n", nifaces);
 
4745
 
 
4746
    for (int i = 0; i < nifaces; i++) {
 
4747
        _debug ("  %s  ", ifreqs[i].ifr_name);
 
4748
        ifaceList.push_back (std::string (ifreqs[i].ifr_name));
 
4749
        printf ("    %s\n", getInterfaceAddrFromName (std::string (ifreqs[i].ifr_name)).c_str());
4485
4750
    }
4486
4751
 
4487
 
    return ifaceList;   
 
4752
    return ifaceList;
4488
4753
}
4489
4754
 
4490
4755
 
4491
 
pj_bool_t stun_sock_on_status (pj_stun_sock *stun_sock, pj_stun_sock_op op, pj_status_t status)
 
4756
pj_bool_t stun_sock_on_status (pj_stun_sock *stun_sock UNUSED, pj_stun_sock_op op UNUSED, pj_status_t status)
4492
4757
{
4493
4758
    if (status == PJ_SUCCESS)
4494
4759
        return PJ_TRUE;
4496
4761
        return PJ_FALSE;
4497
4762
}
4498
4763
 
4499
 
pj_bool_t stun_sock_on_rx_data (pj_stun_sock *stun_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *src_addr, unsigned addr_len)
 
4764
pj_bool_t stun_sock_on_rx_data (pj_stun_sock *stun_sock UNUSED, void *pkt UNUSED, unsigned pkt_len UNUSED, const pj_sockaddr_t *src_addr UNUSED, unsigned addr_len UNUSED)
4500
4765
{
4501
4766
    return PJ_TRUE;
4502
4767
}