managerimpl.cpp 81.9 KB
Newer Older
jpbl's avatar
jpbl committed
1
/*
2
 *  Copyright (C) 2004-2013 Savoir-Faire Linux Inc.
3
 *  Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
jpbl's avatar
jpbl committed
4
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
5
 *  Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
6
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
7
 *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
8
 *  Author: Guillaume Carmel-Archambault <guillaume.carmel-archambault@savoirfairelinux.com>
jpbl's avatar
jpbl committed
9 10
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
11
 *  the Free Software Foundation; either version 3 of the License, or
jpbl's avatar
jpbl committed
12
 *  (at your option) any later version.
13
 *
jpbl's avatar
jpbl committed
14 15 16 17
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
18
 *
jpbl's avatar
jpbl committed
19 20
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
21
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
22 23 24 25 26 27 28 29 30 31 32
 *
 *  Additional permission under GNU GPL version 3 section 7:
 *
 *  If you modify this program, or any covered work, by linking or
 *  combining it with the OpenSSL project's OpenSSL library (or a
 *  modified version of that library), containing parts covered by the
 *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
 *  grants you additional permission to convey the resulting work.
 *  Corresponding Source for a non-source form of such a combination
 *  shall include the source code for the parts of OpenSSL used as well
 *  as that of the covered work.
jpbl's avatar
jpbl committed
33 34
 */

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

39
#include "logger.h"
40
#include "managerimpl.h"
41
#include "account_schema.h"
42

43
#include "global.h"
44
#include "fileutils.h"
45
#include "map_utils.h"
46
#include "sip/sipvoiplink.h"
47
#include "sip/sipaccount.h"
48
#include "sip/sipcall.h"
49
#include "im/instant_messaging.h"
50
#include "sip/sippresence.h"
51

52
#if HAVE_IAX
53
#include "iax/iaxaccount.h"
54
#include "iax/iaxcall.h"
55
#include "iax/iaxvoiplink.h"
56
#endif
57

58
#include "numbercleaner.h"
59 60
#include "config/yamlparser.h"
#include "config/yamlemitter.h"
61

Adrien Béraud's avatar
Adrien Béraud committed
62
#ifndef __ANDROID__
63
#include "audio/alsa/alsalayer.h"
64
#endif
65

66
#include "audio/sound/tonelist.h"
67 68
#include "audio/sound/audiofile.h"
#include "audio/sound/dtmf.h"
69
#include "history/historynamecache.h"
Emeric Vigier's avatar
Emeric Vigier committed
70
#include "history/history.h"
71
#include "manager.h"
72

73
#include "client/configurationmanager.h"
74
#include "client/callmanager.h"
75

76
#ifdef SFL_VIDEO
77
#include "client/video_controls.h"
78
#endif
79

80
#include "conference.h"
81
#include "scoped_lock.h"
82

83
#include <cerrno>
84
#include <algorithm>
85
#include <ctime>
jpbl's avatar
jpbl committed
86 87
#include <cstdlib>
#include <iostream>
88
#include <tr1/functional>
Tristan Matthews's avatar
cleanup  
Tristan Matthews committed
89
#include <iterator>
jpbl's avatar
jpbl committed
90
#include <fstream>
91
#include <sstream>
jpbl's avatar
jpbl committed
92
#include <sys/types.h> // mkdir(2)
93
#include <sys/stat.h>  // mkdir(2)
94

95
ManagerImpl::ManagerImpl() :
96
    preferences(), voipPreferences(),
97
    hookPreference(),  audioPreference(), shortcutPreferences(),
98 99
    hasTriedToRegister_(false), audioCodecFactory(), client_(),
	config_(),
100 101
    currentCallId_(), currentCallMutex_(), audiodriver_(0), dtmfKey_(),
    toneMutex_(), telephoneTone_(), audiofile_(), audioLayerMutex_(),
102
    waitingCalls_(), waitingCallsMutex_(), path_(),
103
    IPToIPMap_(), mainBuffer_(), conferenceMap_(), history_(), finished_(false)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
104
{
105 106 107
    pthread_mutex_init(&currentCallMutex_, NULL);
    pthread_mutex_init(&toneMutex_, NULL);
    pthread_mutex_init(&audioLayerMutex_, NULL);
108
    pthread_mutex_init(&waitingCallsMutex_, NULL);
109
    // initialize random generator for call id
110
    srand(time(NULL));
jpbl's avatar
jpbl committed
111 112
}

113 114 115
ManagerImpl::~ManagerImpl()
{
    // destroy in reverse order of initialization
116
    pthread_mutex_destroy(&waitingCallsMutex_);
117 118 119
    pthread_mutex_destroy(&audioLayerMutex_);
    pthread_mutex_destroy(&toneMutex_);
    pthread_mutex_destroy(&currentCallMutex_);
120 121
}

122
namespace {
123 124

    void copy_over(const std::string &srcPath, const std::string &destPath)
125
    {
126 127
        std::ifstream src(srcPath.c_str());
        std::ofstream dest(destPath.c_str());
128 129 130 131
        dest << src.rdbuf();
        src.close();
        dest.close();
    }
132 133 134 135 136 137 138 139 140 141 142 143
    // Creates a backup of the file at "path" with a .bak suffix appended
    void make_backup(const std::string &path)
    {
        const std::string backup_path(path + ".bak");
        copy_over(path, backup_path);
    }
    // Restore last backup of the configuration file
    void restore_backup(const std::string &path)
    {
        const std::string backup_path(path + ".bak");
        copy_over(backup_path, path);
    }
144 145
}

146
bool ManagerImpl::parseConfiguration()
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
147
{
148
    bool result = true;
149

150
    FILE *file = fopen(path_.c_str(), "rb");
151

152
    try {
153 154
        if (file) {
            Conf::YamlParser parser(file);
155 156 157
            parser.serializeEvents();
            parser.composeEvents();
            parser.constructNativeData();
158
            const int error_count = loadAccountMap(parser);
159
            fclose(file);
160
            if (error_count > 0) {
161
                WARN("Errors while parsing %s", path_.c_str());
162
                result = false;
163
            }
164
        } else {
165 166 167
            WARN("Config file not found: creating default account map");
            loadDefaultAccountMap();
        }
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    } catch (const Conf::YamlParserException &e) {
        // we only want to close the local file here and then rethrow the exception
        fclose(file);
        throw;
    }

    return result;
}

void ManagerImpl::init(const std::string &config_file)
{
    path_ = config_file.empty() ? retrieveConfigPath() : config_file;
    DEBUG("Configuration file path: %s", path_.c_str());

    bool no_errors = true;

    try {
        no_errors = parseConfiguration();
186
    } catch (const Conf::YamlParserException &e) {
187
        ERROR("%s", e.what());
188
        no_errors = false;
189 190
    }

191
    // always back up last error-free configuration
192
    if (no_errors) {
193
        make_backup(path_);
194 195 196 197 198 199 200 201 202 203 204 205
    } else {
        // restore previous configuration
        WARN("Restoring last working configuration");
        try {
            restore_backup(path_);
            parseConfiguration();
        } catch (const Conf::YamlParserException &e) {
            ERROR("%s", e.what());
            WARN("Restoring backup failed, creating default account map");
            loadDefaultAccountMap();
        }
    }
206

207
    initAudioDriver();
208

Tristan Matthews's avatar
Tristan Matthews committed
209
    {
210
        sfl::ScopedLock lock(audioLayerMutex_);
Tristan Matthews's avatar
Tristan Matthews committed
211
        if (audiodriver_) {
212
            {
213
                sfl::ScopedLock toneLock(toneMutex_);
214 215
                telephoneTone_.reset(new TelephoneTone(preferences.getZoneToneChoice(), audiodriver_->getSampleRate()));
            }
216
            dtmfKey_.reset(new DTMF(getMainBuffer().getInternalSamplingRate()));
Tristan Matthews's avatar
Tristan Matthews committed
217
        }
218
    }
219

220
    history_.load(preferences.getHistoryLimit());
221
    registerAccounts();
jpbl's avatar
jpbl committed
222 223
}

Emeric Vigier's avatar
Emeric Vigier committed
224 225 226 227
void ManagerImpl::setPath(const std::string &path) {
	history_.setPath(path);
}

228
#if HAVE_DBUS
229 230
void ManagerImpl::run()
{
231
    DEBUG("Starting client event loop");
232
    client_.event_loop();
233
}
234
#endif
235 236 237

void ManagerImpl::finish()
{
238 239 240 241 242 243 244 245
    if (finished_)
        return;

    finished_ = true;
    // Unset signal handlers
    signal(SIGHUP, SIG_DFL);
    signal(SIGINT, SIG_DFL);
    signal(SIGTERM, SIG_DFL);
246

247
    std::vector<std::string> callList(getCallList());
248
    DEBUG("Hangup %zu remaining call(s)", callList.size());
249

250 251
    for (const auto &item : callList)
        hangupCall(item);
252

253 254
    saveConfig();

255
    unregisterAllAccounts();
256

257
    SIPVoIPLink::destroy();
258 259 260
#if HAVE_IAX
    IAXVoIPLink::unloadAccountMap();
#endif
261

262
    {
263
        sfl::ScopedLock lock(audioLayerMutex_);
264 265 266 267

        delete audiodriver_;
        audiodriver_ = NULL;
    }
268

269
    client_.exit();
jpbl's avatar
jpbl committed
270 271
}

272
bool ManagerImpl::isCurrentCall(const std::string& callId) const
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
273
{
274
    return currentCallId_ == callId;
jpbl's avatar
jpbl committed
275 276
}

277
bool ManagerImpl::hasCurrentCall() const
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
278
{
279
    return not currentCallId_.empty();
jpbl's avatar
jpbl committed
280 281
}

282
std::string
283
ManagerImpl::getCurrentCallId() const
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
284
{
285
    return currentCallId_;
jpbl's avatar
jpbl committed
286 287
}

288 289 290 291 292
void ManagerImpl::unsetCurrentCall()
{
    switchCall("");
}

293
void ManagerImpl::switchCall(const std::string& id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
294
{
295
    sfl::ScopedLock m(currentCallMutex_);
296
    DEBUG("----- Switch current call id to %s -----", id.c_str());
297
    currentCallId_ = id;
jpbl's avatar
jpbl committed
298 299 300 301 302
}

///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
303
/* Main Thread */
Emmanuel Milou's avatar
Emmanuel Milou committed
304

305
bool ManagerImpl::outgoingCall(const std::string& account_id,
306 307 308
                               const std::string& call_id,
                               const std::string& to,
                               const std::string& conf_id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
309
{
310
    if (call_id.empty()) {
311
        DEBUG("New outgoing call abort, missing callid");
Emmanuel Lepage's avatar
Emmanuel Lepage committed
312 313
        return false;
    }
314

315
    // Call ID must be unique
316
    if (isValidCall(call_id)) {
317
        ERROR("Call id already exists in outgoing call");
318 319 320
        return false;
    }

321
    DEBUG("New outgoing call %s to %s", call_id.c_str(), to.c_str());
322

323 324
    stopTone();

325
    std::string current_call_id(getCurrentCallId());
326

327
    std::string prefix(hookPreference.getNumberAddPrefix());
328

329
    std::string to_cleaned(NumberCleaner::clean(to, prefix));
Emmanuel Milou's avatar
Emmanuel Milou committed
330

331 332
    // in any cases we have to detach from current communication
    if (hasCurrentCall()) {
333
        DEBUG("Has current call (%s) put it onhold", current_call_id.c_str());
334

335
        // if this is not a conference and this and is not a conference participant
336
        if (not isConference(current_call_id) and not isConferenceParticipant(current_call_id))
337
            onHoldCall(current_call_id);
338
        else if (isConference(current_call_id) and not isConferenceParticipant(call_id))
339
            detachParticipant(MainBuffer::DEFAULT_ID);
340
    }
341

342
    DEBUG("Selecting account %s", account_id.c_str());
343

344
    // fallback using the default sip account if the specied doesn't exist
Tristan Matthews's avatar
Tristan Matthews committed
345
    std::string use_account_id;
346
    if (!accountExists(account_id)) {
347
        WARN("Account does not exist, trying with default SIP account");
348 349 350 351
        use_account_id = SIPAccount::IP2IP_PROFILE;
    }
    else {
        use_account_id = account_id;
352
    }
353

354
    try {
355
        Call *call = getAccountLink(account_id)->newOutgoingCall(call_id, to_cleaned, use_account_id);
356 357

        // try to reverse match the peer name using the cache
Tristan Matthews's avatar
Tristan Matthews committed
358
        if (call->getDisplayName().empty()) {
359
            const std::string pseudo_contact_name(HistoryNameCache::getInstance().getNameFromHistory(call->getPeerNumber(), call->getAccountId()));
Tristan Matthews's avatar
Tristan Matthews committed
360
            if (not pseudo_contact_name.empty())
361 362
                call->setDisplayName(pseudo_contact_name);
        }
363
        switchCall(call_id);
364
        call->setConfId(conf_id);
365
    } catch (const VoipLinkException &e) {
366
        callFailure(call_id);
367
        ERROR("%s", e.what());
368
        return false;
369 370 371 372
    } catch (ost::Socket *) {
        callFailure(call_id);
        ERROR("Could not bind socket");
        return false;
373 374
    }

375
    getMainBuffer().dumpInfo();
Alexandre Savard's avatar
Alexandre Savard committed
376

377
    return true;
jpbl's avatar
jpbl committed
378 379
}

yanmorin's avatar
 
yanmorin committed
380
//THREAD=Main : for outgoing Call
381
bool ManagerImpl::answerCall(const std::string& call_id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
382
{
383
    bool result = true;
384 385 386 387 388 389
    Call *call = getCallFromCallID(call_id);

    if (call == NULL) {
        ERROR("Call %s is NULL", call_id.c_str());
        return false;
    }
390

391
    // If sflphone is ringing
392
    stopTone();
393

394
    // set playback mode to VOICE
395
    if (audiodriver_) audiodriver_->setPlaybackMode(AudioLayer::VOICE);
396

397
    // store the current call id
398
    std::string current_call_id(getCurrentCallId());
399

400 401
    // in any cases we have to detach from current communication
    if (hasCurrentCall()) {
402

403
        DEBUG("Currently conversing with %s", current_call_id.c_str());
404

405
        if (not isConference(current_call_id) and not isConferenceParticipant(current_call_id)) {
406
            DEBUG("Answer call: Put the current call (%s) on hold", current_call_id.c_str());
407
            onHoldCall(current_call_id);
408
        } else if (isConference(current_call_id) and not isConferenceParticipant(call_id)) {
409
            // if we are talking to a conference and we are answering an incoming call
410
            DEBUG("Detach main participant from conference");
411
            detachParticipant(MainBuffer::DEFAULT_ID);
412 413
        }
    }
414

415
    try {
416
        VoIPLink *link = getAccountLink(call->getAccountId());
417 418
        if (link)
            link->answer(call);
419
    } catch (const std::runtime_error &e) {
420
        ERROR("%s", e.what());
421
        result = false;
422
    }
Alexandre Savard's avatar
Alexandre Savard committed
423

424
    // if it was waiting, it's waiting no more
425
    removeWaitingCall(call_id);
426

427
    // if we dragged this call into a conference already
428
    if (isConferenceParticipant(call_id))
429
        switchCall(call->getConfId());
430
    else
431
        switchCall(call_id);
432

433
    // Connect streams
434
    addStream(call_id);
435

436
    getMainBuffer().dumpInfo();
Alexandre Savard's avatar
Alexandre Savard committed
437

438
    // Start recording if set in preference
439
    if (audioPreference.getIsAlwaysRecording())
440
        toggleRecordingCall(call_id);
441

442
    client_.getCallManager()->callStateChanged(call_id, "CURRENT");
443

444
    return result;
jpbl's avatar
jpbl committed
445 446
}

447 448 449 450 451 452 453
void ManagerImpl::checkAudio()
{
    if (getCallList().empty()) {
        sfl::ScopedLock lock(audioLayerMutex_);
        if (audiodriver_)
            audiodriver_->stopStream();
    }
454

jpbl's avatar
jpbl committed
455 456
}

yanmorin's avatar
 
yanmorin committed
457
//THREAD=Main
458
bool ManagerImpl::hangupCall(const std::string& callId)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
459
{
460
    // store the current call id
461
    std::string currentCallId(getCurrentCallId());
yanmorin's avatar
 
yanmorin committed
462

463
    stopTone();
464

465
    // set playback mode to NONE
466
    if (audiodriver_) audiodriver_->setPlaybackMode(AudioLayer::NONE);
467

468
    DEBUG("Send call state change (HUNGUP) for id %s", callId.c_str());
469
    client_.getCallManager()->callStateChanged(callId, "HUNGUP");
470

471
    /* We often get here when the call was hungup before being created */
472
    if (not isValidCall(callId) and not isIPToIP(callId)) {
473
        DEBUG("Could not hang up call %s, call not valid", callId.c_str());
474
        checkAudio();
475
        return false;
476 477
    }

478 479 480
    // Disconnect streams
    removeStream(callId);

481
    if (isConferenceParticipant(callId)) {
482
        removeParticipant(callId);
483
    } else {
484 485
        // we are not participating in a conference, current call switched to ""
        if (not isConference(currentCallId))
486
            unsetCurrentCall();
487
    }
488

489
    if (isIPToIP(callId)) {
490
        /* Direct IP to IP call */
491
        try {
492
            Call * call = SIPVoIPLink::instance()->getSipCall(callId);
493 494
            if (call) {
                history_.addCall(call, preferences.getHistoryLimit());
495
                SIPVoIPLink::instance()->hangup(callId, 0);
496
                checkAudio();
497 498
                saveHistory();
            }
499
        } catch (const VoipLinkException &e) {
500
            ERROR("%s", e.what());
501
            return false;
502
        }
503
    } else {
504
        Call * call = getCallFromCallID(callId);
505 506
        if (call) {
            history_.addCall(call, preferences.getHistoryLimit());
507
            VoIPLink *link = getAccountLink(call->getAccountId());
508
            link->hangup(callId, 0);
509
            checkAudio();
510 511
            saveHistory();
        }
512
    }
513

514
    getMainBuffer().dumpInfo();
515
    return true;
jpbl's avatar
jpbl committed
516 517
}

518
bool ManagerImpl::hangupConference(const std::string& id)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
519
{
520
    DEBUG("Hangup conference %s", id.c_str());
Alexandre Savard's avatar
Alexandre Savard committed
521

522
    ConferenceMap::iterator iter_conf = conferenceMap_.find(id);
Alexandre Savard's avatar
Alexandre Savard committed
523

524
    if (iter_conf != conferenceMap_.end()) {
525
        Conference *conf = iter_conf->second;
Alexandre Savard's avatar
Alexandre Savard committed
526

527 528
        if (conf) {
            ParticipantSet participants(conf->getParticipantList());
529

530 531
            for (const auto &item : participants)
                hangupCall(item);
532
        } else {
533
            ERROR("No such conference %s", id.c_str());
534 535
            return false;
        }
536
    }
Alexandre Savard's avatar
Alexandre Savard committed
537

538
    unsetCurrentCall();
539

540
    getMainBuffer().dumpInfo();
541

542
    return true;
Alexandre Savard's avatar
Alexandre Savard committed
543 544
}

jpbl's avatar
jpbl committed
545

yanmorin's avatar
 
yanmorin committed
546
//THREAD=Main
547
bool ManagerImpl::onHoldCall(const std::string& callId)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
548
{
549
    bool result = true;
550

551
    stopTone();
552

553
    std::string current_call_id(getCurrentCallId());
554

555
    try {
556
        if (isIPToIP(callId)) {
557
            SIPVoIPLink::instance()->onhold(callId);
558 559 560
        } else {
            /* Classic call, attached to an account */
            std::string account_id(getAccountFromCall(callId));
561

562
            if (account_id.empty()) {
563
                DEBUG("Account ID %s or callid %s doesn't exist in call onHold", account_id.c_str(), callId.c_str());
564
                return false;
565
            }
566 567 568 569

            getAccountLink(account_id)->onhold(callId);
        }
    } catch (const VoipLinkException &e) {
570
        ERROR("%s", e.what());
571
        result = false;
572
    }
573

574
    // Unbind calls in main buffer
575
    removeStream(callId);
576

577
    // Remove call from teh queue if it was still there
578
    removeWaitingCall(callId);
579

580
    // keeps current call id if the action is not holding this call or a new outgoing call
581
    // this could happen in case of a conference
582
    if (current_call_id == callId)
583
        unsetCurrentCall();
584

585
    client_.getCallManager()->callStateChanged(callId, "HOLD");
586

587
    getMainBuffer().dumpInfo();
588
    return result;
yanmorin's avatar
 
yanmorin committed
589 590 591
}

//THREAD=Main
592
bool ManagerImpl::offHoldCall(const std::string& callId)
Emmanuel Milou's avatar
[#2402]  
Emmanuel Milou committed
593
{
594
    bool result = true;
595

596
    stopTone();
597

Tristan Matthews's avatar
Tristan Matthews committed
598
    const std::string currentCallId(getCurrentCallId());
599

Tristan Matthews's avatar
Tristan Matthews committed
600
    // Place current call on hold if it isn't
601
    if (hasCurrentCall()) {
Tristan Matthews's avatar
Tristan Matthews committed
602
        if (not isConference(currentCallId) and not isConferenceParticipant(currentCallId)) {
603
            DEBUG("Has current call (%s), put on hold", currentCallId.c_str());
604
            onHoldCall(currentCallId);
605 606
        } else if (isConference(currentCallId) && callId != currentCallId) {
            holdConference(currentCallId);
607
        } else if (isConference(currentCallId) and not isConferenceParticipant(callId))
608
            detachParticipant(MainBuffer::DEFAULT_ID);
609
    }
alexandresavard's avatar
alexandresavard committed
610

611
    if (isIPToIP(callId))
Tristan Matthews's avatar
Tristan Matthews committed
612
        SIPVoIPLink::instance()->offhold(callId);
613
    else {
614
        /* Classic call, attached to an account */
615
        Call * call = getCallFromCallID(callId);
616

617
        if (call)
618
            getAccountLink(call->getAccountId())->offhold(callId);
619 620
        else
            result = false;
621
    }
622

623
    client_.getCallManager()->callStateChanged(callId, "UNHOLD");
624

625
    if (isConferenceParticipant(callId)) {
626
        Call *call = getCallFromCallID(callId);
627
        if (call)
628
            switchCall(call->getConfId());
629 630
        else
            result = false;
631
    } else
632
        switchCall(callId);
633