id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
751,764
ringbufferpool.cpp
savoirfairelinux_jami-daemon/src/media/audio/ringbufferpool.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ringbufferpool.h" #include "ringbuffer.h" #include "ring_types.h" // for SIZEBUF #include "logger.h" #include <limits> #include <utility> // for std::pair #include <cstring> #include <algorithm> namespace jami { const char* const RingBufferPool::DEFAULT_ID = "audiolayer_id"; RingBufferPool::RingBufferPool() : defaultRingBuffer_(createRingBuffer(DEFAULT_ID)) {} RingBufferPool::~RingBufferPool() { readBindingsMap_.clear(); defaultRingBuffer_.reset(); // Verify ringbuffer not removed yet // XXXX: With a good design this should never happen! :-P for (const auto& item : ringBufferMap_) { const auto& weak = item.second; if (not weak.expired()) JAMI_WARNING("Leaking RingBuffer '{}'", item.first); } } void RingBufferPool::setInternalSamplingRate(unsigned sr) { std::lock_guard lk(stateLock_); if (sr != internalAudioFormat_.sample_rate) { flushAllBuffers(); internalAudioFormat_.sample_rate = sr; } } void RingBufferPool::setInternalAudioFormat(AudioFormat format) { std::lock_guard lk(stateLock_); if (format != internalAudioFormat_) { flushAllBuffers(); internalAudioFormat_ = format; for (auto& wrb : ringBufferMap_) if (auto rb = wrb.second.lock()) rb->setFormat(internalAudioFormat_); } } std::shared_ptr<RingBuffer> RingBufferPool::getRingBuffer(const std::string& id) { std::lock_guard lk(stateLock_); const auto& it = ringBufferMap_.find(id); if (it != ringBufferMap_.cend()) { if (const auto& sptr = it->second.lock()) return sptr; ringBufferMap_.erase(it); } return nullptr; } std::shared_ptr<RingBuffer> RingBufferPool::getRingBuffer(const std::string& id) const { std::lock_guard lk(stateLock_); const auto& it = ringBufferMap_.find(id); if (it != ringBufferMap_.cend()) return it->second.lock(); return nullptr; } std::shared_ptr<RingBuffer> RingBufferPool::createRingBuffer(const std::string& id) { std::lock_guard lk(stateLock_); auto rbuf = getRingBuffer(id); if (rbuf) { JAMI_DEBUG("Ringbuffer already exists for id '{}'", id); return rbuf; } rbuf.reset(new RingBuffer(id, SIZEBUF, internalAudioFormat_)); ringBufferMap_.emplace(id, std::weak_ptr<RingBuffer>(rbuf)); return rbuf; } const RingBufferPool::ReadBindings* RingBufferPool::getReadBindings(const std::string& ringbufferId) const { const auto& iter = readBindingsMap_.find(ringbufferId); return iter != readBindingsMap_.cend() ? &iter->second : nullptr; } RingBufferPool::ReadBindings* RingBufferPool::getReadBindings(const std::string& ringbufferId) { const auto& iter = readBindingsMap_.find(ringbufferId); return iter != readBindingsMap_.cend() ? &iter->second : nullptr; } void RingBufferPool::removeReadBindings(const std::string& ringbufferId) { if (not readBindingsMap_.erase(ringbufferId)) JAMI_ERROR("Ringbuffer {} does not exist!", ringbufferId); } /** * Make given ringbuffer a reader of given ring buffer */ void RingBufferPool::addReaderToRingBuffer(const std::shared_ptr<RingBuffer>& rbuf, const std::string& ringbufferId) { if (ringbufferId != DEFAULT_ID and rbuf->getId() == ringbufferId) JAMI_WARNING("RingBuffer has a readoffset on itself"); rbuf->createReadOffset(ringbufferId); readBindingsMap_[ringbufferId].insert(rbuf); // bindings list created if not existing JAMI_DEBUG("Bind rbuf '{}' to ringbuffer '{}'", rbuf->getId(), ringbufferId); } void RingBufferPool::removeReaderFromRingBuffer(const std::shared_ptr<RingBuffer>& rbuf, const std::string& ringbufferId) { if (auto bindings = getReadBindings(ringbufferId)) { bindings->erase(rbuf); if (bindings->empty()) removeReadBindings(ringbufferId); } rbuf->removeReadOffset(ringbufferId); } void RingBufferPool::bindRingbuffers(const std::string& ringbufferId1, const std::string& ringbufferId2) { JAMI_LOG("Bind ringbuffer {} to ringbuffer {}", ringbufferId1, ringbufferId2); const auto& rb1 = getRingBuffer(ringbufferId1); if (not rb1) { JAMI_ERROR("No ringbuffer associated with id '{}'", ringbufferId1); return; } const auto& rb2 = getRingBuffer(ringbufferId2); if (not rb2) { JAMI_ERROR("No ringbuffer associated to id '{}'", ringbufferId2); return; } std::lock_guard lk(stateLock_); addReaderToRingBuffer(rb1, ringbufferId2); addReaderToRingBuffer(rb2, ringbufferId1); } void RingBufferPool::bindHalfDuplexOut(const std::string& processId, const std::string& ringbufferId) { /* This method is used only for active ringbuffers, if this ringbuffer does not exist, * do nothing */ if (const auto& rb = getRingBuffer(ringbufferId)) { std::lock_guard lk(stateLock_); addReaderToRingBuffer(rb, processId); } } void RingBufferPool::unbindRingbuffers(const std::string& ringbufferId1, const std::string& ringbufferId2) { JAMI_LOG("Unbind ringbuffers {} and {}", ringbufferId1, ringbufferId2); const auto& rb1 = getRingBuffer(ringbufferId1); if (not rb1) { JAMI_ERROR("No ringbuffer associated to id '{}'", ringbufferId1); return; } const auto& rb2 = getRingBuffer(ringbufferId2); if (not rb2) { JAMI_ERROR("No ringbuffer associated to id '{}'", ringbufferId2); return; } std::lock_guard lk(stateLock_); removeReaderFromRingBuffer(rb1, ringbufferId2); removeReaderFromRingBuffer(rb2, ringbufferId1); } void RingBufferPool::unBindHalfDuplexOut(const std::string& process_id, const std::string& ringbufferId) { std::lock_guard lk(stateLock_); if (const auto& rb = getRingBuffer(ringbufferId)) removeReaderFromRingBuffer(rb, process_id); } void RingBufferPool::unBindAllHalfDuplexOut(const std::string& ringbufferId) { const auto& rb = getRingBuffer(ringbufferId); if (not rb) { JAMI_ERROR("No ringbuffer associated to id '{}'", ringbufferId); return; } std::lock_guard lk(stateLock_); auto bindings = getReadBindings(ringbufferId); if (not bindings) return; const auto bindings_copy = *bindings; // temporary copy for (const auto& rbuf : bindings_copy) { removeReaderFromRingBuffer(rb, rbuf->getId()); } } void RingBufferPool::unBindAll(const std::string& ringbufferId) { JAMI_LOG("Unbind ringbuffer {} from all bound ringbuffers", ringbufferId); const auto& rb = getRingBuffer(ringbufferId); if (not rb) { JAMI_ERROR("No ringbuffer associated to id '{}'", ringbufferId); return; } std::lock_guard lk(stateLock_); auto bindings = getReadBindings(ringbufferId); if (not bindings) return; const auto bindings_copy = *bindings; // temporary copy for (const auto& rbuf : bindings_copy) { removeReaderFromRingBuffer(rbuf, ringbufferId); removeReaderFromRingBuffer(rb, rbuf->getId()); } } std::shared_ptr<AudioFrame> RingBufferPool::getData(const std::string& ringbufferId) { std::lock_guard lk(stateLock_); const auto bindings = getReadBindings(ringbufferId); if (not bindings) return {}; // No mixing if (bindings->size() == 1) return (*bindings->cbegin())->get(ringbufferId); auto mixBuffer = std::make_shared<AudioFrame>(internalAudioFormat_); auto mixed = false; for (const auto& rbuf : *bindings) { if (auto b = rbuf->get(ringbufferId)) { mixed = true; mixBuffer->mix(*b); // voice is true if any of mixed frames has voice mixBuffer->has_voice |= b->has_voice; } } return mixed ? mixBuffer : nullptr; } bool RingBufferPool::waitForDataAvailable(const std::string& ringbufferId, const std::chrono::microseconds& max_wait) const { std::unique_lock<std::recursive_mutex> lk(stateLock_); // convert to absolute time const auto deadline = std::chrono::high_resolution_clock::now() + max_wait; auto bindings = getReadBindings(ringbufferId); if (not bindings) return 0; const auto bindings_copy = *bindings; // temporary copy for (const auto& rbuf : bindings_copy) { lk.unlock(); if (rbuf->waitForDataAvailable(ringbufferId, deadline) == 0) return false; lk.lock(); } return true; } std::shared_ptr<AudioFrame> RingBufferPool::getAvailableData(const std::string& ringbufferId) { std::lock_guard lk(stateLock_); auto bindings = getReadBindings(ringbufferId); if (not bindings) return 0; // No mixing if (bindings->size() == 1) { return (*bindings->cbegin())->get(ringbufferId); } size_t availableFrames = 0; for (const auto& rbuf : *bindings) availableFrames = std::min(availableFrames, rbuf->availableForGet(ringbufferId)); if (availableFrames == 0) return {}; auto buf = std::make_shared<AudioFrame>(internalAudioFormat_); for (const auto& rbuf : *bindings) { if (auto b = rbuf->get(ringbufferId)) { buf->mix(*b); // voice is true if any of mixed frames has voice buf->has_voice |= b->has_voice; } } return buf; } size_t RingBufferPool::availableForGet(const std::string& ringbufferId) const { std::lock_guard lk(stateLock_); const auto bindings = getReadBindings(ringbufferId); if (not bindings) return 0; // No mixing if (bindings->size() == 1) { return (*bindings->begin())->availableForGet(ringbufferId); } size_t availableSamples = std::numeric_limits<size_t>::max(); for (const auto& rbuf : *bindings) { const size_t nbSamples = rbuf->availableForGet(ringbufferId); if (nbSamples != 0) availableSamples = std::min(availableSamples, nbSamples); } return availableSamples != std::numeric_limits<size_t>::max() ? availableSamples : 0; } size_t RingBufferPool::discard(size_t toDiscard, const std::string& ringbufferId) { std::lock_guard lk(stateLock_); const auto bindings = getReadBindings(ringbufferId); if (not bindings) return 0; for (const auto& rbuf : *bindings) rbuf->discard(toDiscard, ringbufferId); return toDiscard; } void RingBufferPool::flush(const std::string& ringbufferId) { std::lock_guard lk(stateLock_); const auto bindings = getReadBindings(ringbufferId); if (not bindings) return; for (const auto& rbuf : *bindings) rbuf->flush(ringbufferId); } void RingBufferPool::flushAllBuffers() { std::lock_guard lk(stateLock_); for (auto item = ringBufferMap_.begin(); item != ringBufferMap_.end();) { if (const auto rb = item->second.lock()) { rb->flushAll(); ++item; } else { // Use this version of erase to avoid using invalidated iterator item = ringBufferMap_.erase(item); } } } bool RingBufferPool::isAudioMeterActive(const std::string& id) { std::lock_guard lk(stateLock_); if (!id.empty()) { if (auto rb = getRingBuffer(id)) { return rb->isAudioMeterActive(); } } else { for (auto item = ringBufferMap_.begin(); item != ringBufferMap_.end(); ++item) { if (const auto rb = item->second.lock()) { if (rb->isAudioMeterActive()) { return true; } } } } return false; } void RingBufferPool::setAudioMeterState(const std::string& id, bool state) { std::lock_guard lk(stateLock_); if (!id.empty()) { if (auto rb = getRingBuffer(id)) { rb->setAudioMeterState(state); } } else { for (auto item = ringBufferMap_.begin(); item != ringBufferMap_.end(); ++item) { if (const auto rb = item->second.lock()) { rb->setAudioMeterState(state); } } } } } // namespace jami
12,956
C++
.cpp
384
28.231771
101
0.66704
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,765
resampler.cpp
savoirfairelinux_jami-daemon/src/media/audio/resampler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" #include "logger.h" #include "resampler.h" extern "C" { #include <libswresample/swresample.h> } namespace jami { Resampler::Resampler() : swrCtx_(swr_alloc()) , initCount_(0) {} Resampler::~Resampler() { swr_free(&swrCtx_); } void Resampler::reinit(const AVFrame* in, const AVFrame* out) { // NOTE swr_set_matrix should be called on an uninitialized context auto swrCtx = swr_alloc(); if (!swrCtx) { JAMI_ERR() << "Unable to allocate resampler context"; throw std::bad_alloc(); } av_opt_set_chlayout(swrCtx, "ichl", &in->ch_layout, 0); av_opt_set_int(swrCtx, "isr", in->sample_rate, 0); av_opt_set_sample_fmt(swrCtx, "isf", static_cast<AVSampleFormat>(in->format), 0); av_opt_set_chlayout(swrCtx, "ochl", &out->ch_layout, 0); av_opt_set_int(swrCtx, "osr", out->sample_rate, 0); av_opt_set_sample_fmt(swrCtx, "osf", static_cast<AVSampleFormat>(out->format), 0); /** * Downmixing from 5.1 requires extra setup, since libswresample is unable to do it * automatically (not yet implemented). * * Source: https://www.atsc.org/wp-content/uploads/2015/03/A52-201212-17.pdf * Section 7.8.2 for the algorithm * Tables 5.9 and 5.10 for the coefficients clev and slev * * LFE downmixing is optional, so any coefficient can be used, we use +6dB for mono and * +0dB in each channel for stereo. */ if (in->ch_layout.u.mask == AV_CH_LAYOUT_5POINT1 || in->ch_layout.u.mask == AV_CH_LAYOUT_5POINT1_BACK) { // NOTE: MSVC is unable to allocate dynamic size arrays on the stack if (out->ch_layout.nb_channels == 2) { double matrix[2][6]; // L = 1.0*FL + 0.707*FC + 0.707*BL + 1.0*LFE matrix[0][0] = 1; matrix[0][1] = 0; matrix[0][2] = 0.707; matrix[0][3] = 1; matrix[0][4] = 0.707; matrix[0][5] = 0; // R = 1.0*FR + 0.707*FC + 0.707*BR + 1.0*LFE matrix[1][0] = 0; matrix[1][1] = 1; matrix[1][2] = 0.707; matrix[1][3] = 1; matrix[1][4] = 0; matrix[1][5] = 0.707; swr_set_matrix(swrCtx, matrix[0], 6); } else { double matrix[1][6]; // M = 1.0*FL + 1.414*FC + 1.0*FR + 0.707*BL + 0.707*BR + 2.0*LFE matrix[0][0] = 1; matrix[0][1] = 1; matrix[0][2] = 1.414; matrix[0][3] = 2; matrix[0][4] = 0.707; matrix[0][5] = 0.707; swr_set_matrix(swrCtx, matrix[0], 6); } } if (swr_init(swrCtx) >= 0) { std::swap(swrCtx_, swrCtx); swr_free(&swrCtx); ++initCount_; } else { std::string msg = "Failed to initialize resampler context"; JAMI_ERR() << msg; throw std::runtime_error(msg); } } int Resampler::resample(const AVFrame* input, AVFrame* output) { if (!initCount_) reinit(input, output); int ret = swr_convert_frame(swrCtx_, output, input); if (ret & AVERROR_INPUT_CHANGED || ret & AVERROR_OUTPUT_CHANGED) { // Under certain conditions, the resampler reinits itself in an infinite loop. This is // indicative of an underlying problem in the code. This check is so the backtrace // doesn't get mangled with a bunch of calls to Resampler::resample if (initCount_ > 1) { JAMI_ERROR("Infinite loop detected in audio resampler, please open an issue on https://git.jami.net"); throw std::runtime_error("Resampler"); } reinit(input, output); return resample(input, output); } else if (ret < 0) { JAMI_ERROR("Failed to resample frame"); return -1; } // Resampling worked, reset count to 1 so reinit isn't called again initCount_ = 1; return 0; } std::unique_ptr<AudioFrame> Resampler::resample(std::unique_ptr<AudioFrame>&& in, const AudioFormat& format) { if (in->pointer()->sample_rate == (int) format.sample_rate && in->pointer()->ch_layout.nb_channels == (int) format.nb_channels && (AVSampleFormat) in->pointer()->format == format.sampleFormat) { return std::move(in); } auto output = std::make_unique<AudioFrame>(format); resample(in->pointer(), output->pointer()); output->has_voice = in->has_voice; return output; } std::shared_ptr<AudioFrame> Resampler::resample(std::shared_ptr<AudioFrame>&& in, const AudioFormat& format) { if (not in) { return {}; } auto inPtr = in->pointer(); if (inPtr == nullptr) { return {}; } if (inPtr->sample_rate == (int) format.sample_rate && inPtr->ch_layout.nb_channels == (int) format.nb_channels && (AVSampleFormat) inPtr->format == format.sampleFormat) { return std::move(in); } auto output = std::make_shared<AudioFrame>(format); if (auto outPtr = output->pointer()) { resample(inPtr, outPtr); output->has_voice = in->has_voice; return output; } return {}; } } // namespace jami
5,863
C++
.cpp
160
30.3
114
0.608091
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,766
audio_input.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio_input.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audio_frame_resizer.h" #include "audio_input.h" #include "jami/media_const.h" #include "fileutils.h" // access #include "manager.h" #include "media_decoder.h" #include "resampler.h" #include "ringbuffer.h" #include "ringbufferpool.h" #include "tracepoint.h" #include <future> #include <memory> namespace jami { static constexpr auto MS_PER_PACKET = std::chrono::milliseconds(20); AudioInput::AudioInput(const std::string& id) : id_(id) , format_(Manager::instance().getRingBufferPool().getInternalAudioFormat()) , frameSize_(format_.sample_rate * MS_PER_PACKET.count() / 1000) , resampler_(new Resampler) , resizer_(new AudioFrameResizer(format_, frameSize_, [this](std::shared_ptr<AudioFrame>&& f) { frameResized(std::move(f)); })) , deviceGuard_() , loop_([] { return true; }, [this] { process(); }, [] {}) { JAMI_DEBUG("Creating audio input with id: {}", id_); ringBuf_ = Manager::instance().getRingBufferPool().createRingBuffer(id_); } AudioInput::AudioInput(const std::string& id, const std::string& resource) : AudioInput(id) { switchInput(resource); } AudioInput::~AudioInput() { if (playingFile_) { Manager::instance().getRingBufferPool().unBindHalfDuplexOut(RingBufferPool::DEFAULT_ID, id_); Manager::instance().getRingBufferPool().unBindHalfDuplexOut(id_, id_); } ringBuf_.reset(); loop_.join(); Manager::instance().getRingBufferPool().flush(id_); } void AudioInput::process() { readFromDevice(); } void AudioInput::updateStartTime(int64_t start) { if (decoder_) { decoder_->updateStartTime(start); } } void AudioInput::frameResized(std::shared_ptr<AudioFrame>&& ptr) { std::shared_ptr<AudioFrame> frame = std::move(ptr); frame->pointer()->pts = sent_samples; sent_samples += frame->pointer()->nb_samples; notify(std::static_pointer_cast<MediaFrame>(frame)); } void AudioInput::setSeekTime(int64_t time) { if (decoder_) { decoder_->setSeekTime(time); } } void AudioInput::readFromDevice() { { std::lock_guard lk(resourceMutex_); if (decodingFile_) while (ringBuf_ && ringBuf_->isEmpty()) readFromFile(); if (playingFile_) { while (ringBuf_ && ringBuf_->getLength(id_) == 0) readFromQueue(); } } // Note: read for device is called in an audio thread and we don't // want to have a loop which takes 100% of the CPU. // Here, we basically want to mix available data without any glitch // and even if one buffer doesn't have audio data (call in hold, // connections issues, etc). So mix every MS_PER_PACKET std::this_thread::sleep_until(wakeUp_); wakeUp_ += MS_PER_PACKET; auto& bufferPool = Manager::instance().getRingBufferPool(); auto audioFrame = bufferPool.getData(id_); if (not audioFrame) return; if (muteState_) { libav_utils::fillWithSilence(audioFrame->pointer()); audioFrame->has_voice = false; // force no voice activity when muted } std::lock_guard lk(fmtMutex_); if (bufferPool.getInternalAudioFormat() != format_) audioFrame = resampler_->resample(std::move(audioFrame), format_); resizer_->enqueue(std::move(audioFrame)); if (recorderCallback_ && settingMS_.exchange(false)) { recorderCallback_(MediaStream("a:local", format_, sent_samples)); } jami_tracepoint(audio_input_read_from_device_end, id_.c_str()); } void AudioInput::readFromQueue() { if (!decoder_) return; if (paused_ || !decoder_->emitFrame(true)) { std::this_thread::sleep_for(MS_PER_PACKET); } } void AudioInput::readFromFile() { if (!decoder_) return; const auto ret = decoder_->decode(); switch (ret) { case MediaDemuxer::Status::Success: break; case MediaDemuxer::Status::EndOfFile: createDecoder(); break; case MediaDemuxer::Status::ReadError: JAMI_ERR() << "Failed to decode frame"; break; case MediaDemuxer::Status::ReadBufferOverflow: JAMI_ERR() << "Read buffer overflow detected"; break; case MediaDemuxer::Status::FallBack: case MediaDemuxer::Status::RestartRequired: break; } } bool AudioInput::initDevice(const std::string& device) { devOpts_ = {}; devOpts_.input = device; devOpts_.channel = format_.nb_channels; devOpts_.framerate = format_.sample_rate; deviceGuard_ = Manager::instance().startAudioStream(AudioDeviceType::CAPTURE); playingDevice_ = true; return true; } void AudioInput::configureFilePlayback(const std::string& path, std::shared_ptr<MediaDemuxer>& demuxer, int index) { decoder_.reset(); devOpts_ = {}; devOpts_.input = path; devOpts_.name = path; auto decoder = std::make_unique<MediaDecoder>(demuxer, index, [this](std::shared_ptr<MediaFrame>&& frame) { if (muteState_) libav_utils::fillWithSilence(frame->pointer()); if (ringBuf_) ringBuf_->put(std::static_pointer_cast<AudioFrame>(frame)); }); decoder->emulateRate(); decoder->setInterruptCallback( [](void* data) -> int { return not static_cast<AudioInput*>(data)->isCapturing(); }, this); // have file audio mixed into the local buffer so it gets played Manager::instance().getRingBufferPool().bindHalfDuplexOut(RingBufferPool::DEFAULT_ID, id_); // Bind to itself to be able to read from the ringbuffer Manager::instance().getRingBufferPool().bindHalfDuplexOut(id_, id_); deviceGuard_ = Manager::instance().startAudioStream(AudioDeviceType::PLAYBACK); wakeUp_ = std::chrono::steady_clock::now() + MS_PER_PACKET; playingFile_ = true; decoder_ = std::move(decoder); resource_ = path; loop_.start(); } void AudioInput::setPaused(bool paused) { if (paused) { Manager::instance().getRingBufferPool().unBindHalfDuplexOut(RingBufferPool::DEFAULT_ID, id_); deviceGuard_.reset(); } else { Manager::instance().getRingBufferPool().bindHalfDuplexOut(RingBufferPool::DEFAULT_ID, id_); deviceGuard_ = Manager::instance().startAudioStream(AudioDeviceType::PLAYBACK); } paused_ = paused; } void AudioInput::flushBuffers() { if (decoder_) { decoder_->flushBuffers(); } } bool AudioInput::initFile(const std::string& path) { if (access(path.c_str(), R_OK) != 0) { JAMI_ERROR("File '{}' not available", path); return false; } devOpts_ = {}; devOpts_.input = path; devOpts_.name = path; devOpts_.loop = "1"; // sets devOpts_'s sample rate and number of channels if (!createDecoder()) { JAMI_WARN() << "Unable to decode audio from file, switching back to default device"; return initDevice(""); } wakeUp_ = std::chrono::steady_clock::now() + MS_PER_PACKET; // have file audio mixed into the local buffer so it gets played Manager::instance().getRingBufferPool().bindHalfDuplexOut(RingBufferPool::DEFAULT_ID, id_); decodingFile_ = true; deviceGuard_ = Manager::instance().startAudioStream(AudioDeviceType::PLAYBACK); return true; } std::shared_future<DeviceParams> AudioInput::switchInput(const std::string& resource) { // Always switch inputs, even if it's the same resource, so audio will be in sync with video std::unique_lock lk(resourceMutex_); JAMI_DEBUG("Switching audio source from {} to {}", resource_, resource); auto oldGuard = std::move(deviceGuard_); decoder_.reset(); if (decodingFile_) { decodingFile_ = false; Manager::instance().getRingBufferPool().unBindHalfDuplexOut(RingBufferPool::DEFAULT_ID, id_); } playingDevice_ = false; resource_ = resource; devOptsFound_ = false; std::promise<DeviceParams> p; foundDevOpts_.swap(p); if (resource_.empty()) { if (initDevice("")) foundDevOpts(devOpts_); } else { static const std::string& sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = resource_.find(sep); if (pos == std::string::npos) return {}; const auto prefix = resource_.substr(0, pos); if ((pos + sep.size()) >= resource_.size()) return {}; const auto suffix = resource_.substr(pos + sep.size()); bool ready = false; if (prefix == libjami::Media::VideoProtocolPrefix::FILE) ready = initFile(suffix); else ready = initDevice(suffix); if (ready) foundDevOpts(devOpts_); } futureDevOpts_ = foundDevOpts_.get_future().share(); wakeUp_ = std::chrono::steady_clock::now() + MS_PER_PACKET; lk.unlock(); loop_.start(); if (onSuccessfulSetup_) onSuccessfulSetup_(MEDIA_AUDIO, 0); return futureDevOpts_; } void AudioInput::foundDevOpts(const DeviceParams& params) { if (!devOptsFound_) { devOptsFound_ = true; foundDevOpts_.set_value(params); } } void AudioInput::setRecorderCallback( const std::function<void(const MediaStream& ms)>& cb) { settingMS_.exchange(true); recorderCallback_ = cb; if (decoder_) decoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); } bool AudioInput::createDecoder() { decoder_.reset(); if (devOpts_.input.empty()) { foundDevOpts(devOpts_); return false; } auto decoder = std::make_unique<MediaDecoder>([this](std::shared_ptr<MediaFrame>&& frame) { if (ringBuf_) ringBuf_->put(std::static_pointer_cast<AudioFrame>(frame)); }); // NOTE don't emulate rate, file is read as frames are needed decoder->setInterruptCallback( [](void* data) -> int { return not static_cast<AudioInput*>(data)->isCapturing(); }, this); if (decoder->openInput(devOpts_) < 0) { JAMI_ERR() << "Unable to open input '" << devOpts_.input << "'"; foundDevOpts(devOpts_); return false; } if (decoder->setupAudio() < 0) { JAMI_ERR() << "Unable to setup decoder for '" << devOpts_.input << "'"; foundDevOpts(devOpts_); return false; } auto ms = decoder->getStream(devOpts_.input); devOpts_.channel = ms.nbChannels; devOpts_.framerate = ms.sampleRate; JAMI_DBG() << "Created audio decoder: " << ms; decoder_ = std::move(decoder); foundDevOpts(devOpts_); decoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); return true; } void AudioInput::setFormat(const AudioFormat& fmt) { std::lock_guard lk(fmtMutex_); format_ = fmt; resizer_->setFormat(format_, format_.sample_rate * MS_PER_PACKET.count() / 1000); } void AudioInput::setMuted(bool isMuted) { JAMI_WARN("Audio Input muted [%s]", isMuted ? "YES" : "NO"); muteState_ = isMuted; } MediaStream AudioInput::getInfo() const { std::lock_guard lk(fmtMutex_); return MediaStream("a:local", format_, sent_samples); } MediaStream AudioInput::getInfo(const std::string& name) const { std::lock_guard lk(fmtMutex_); auto ms = MediaStream(name, format_, sent_samples); return ms; } } // namespace jami
12,395
C++
.cpp
371
27.622642
102
0.642959
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,767
audiolayer.cpp
savoirfairelinux_jami-daemon/src/media/audio/audiolayer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audiolayer.h" #include "logger.h" #include "manager.h" #include "audio/ringbufferpool.h" #include "audio/resampler.h" #include "tonecontrol.h" #include "client/ring_signal.h" #include "audio-processing/null_audio_processor.h" #include "tracepoint.h" #if HAVE_WEBRTC_AP #include "audio-processing/webrtc.h" #endif #if HAVE_SPEEXDSP #include "audio-processing/speex.h" #endif #include <ctime> #include <algorithm> namespace jami { AudioLayer::AudioLayer(const AudioPreference& pref) : isCaptureMuted_(pref.getCaptureMuted()) , isPlaybackMuted_(pref.getPlaybackMuted()) , captureGain_(pref.getVolumemic()) , playbackGain_(pref.getVolumespkr()) , pref_(pref) , mainRingBuffer_( Manager::instance().getRingBufferPool().getRingBuffer(RingBufferPool::DEFAULT_ID)) , audioFormat_(Manager::instance().getRingBufferPool().getInternalAudioFormat()) , audioInputFormat_(Manager::instance().getRingBufferPool().getInternalAudioFormat()) , urgentRingBuffer_("urgentRingBuffer_id", SIZEBUF, audioFormat_) , resampler_(new Resampler) , lastNotificationTime_() { urgentRingBuffer_.createReadOffset(RingBufferPool::DEFAULT_ID); JAMI_LOG("[audiolayer] AGC: {:d}, noiseReduce: {:s}, VAD: {:d}, echoCancel: {:s}, audioProcessor: {:s}", pref_.isAGCEnabled(), pref.getNoiseReduce(), pref.getVadEnabled(), pref.getEchoCanceller(), pref.getAudioProcessor()); } AudioLayer::~AudioLayer() {} void AudioLayer::hardwareFormatAvailable(AudioFormat playback, size_t bufSize) { JAMI_LOG("Hardware audio format available : {:s} {}", playback.toString(), bufSize); audioFormat_ = Manager::instance().hardwareAudioFormatChanged(playback); audioInputFormat_.sampleFormat = audioFormat_.sampleFormat; urgentRingBuffer_.setFormat(audioFormat_); nativeFrameSize_ = bufSize; } void AudioLayer::hardwareInputFormatAvailable(AudioFormat capture) { JAMI_LOG("Hardware input audio format available : {:s}", capture.toString()); } void AudioLayer::devicesChanged() { emitSignal<libjami::AudioSignal::DeviceEvent>(); } void AudioLayer::flushMain() { Manager::instance().getRingBufferPool().flushAllBuffers(); } void AudioLayer::flushUrgent() { urgentRingBuffer_.flushAll(); } void AudioLayer::flush() { Manager::instance().getRingBufferPool().flushAllBuffers(); urgentRingBuffer_.flushAll(); } void AudioLayer::playbackChanged(bool started) { playbackStarted_ = started; } void AudioLayer::recordChanged(bool started) { std::lock_guard lock(audioProcessorMutex); if (started) { // create audio processor createAudioProcessor(); } else { // destroy audio processor destroyAudioProcessor(); } recordStarted_ = started; } // helper function static inline bool shouldUseAudioProcessorEchoCancel(bool hasNativeAEC, const std::string& echoCancellerPref) { return // user doesn't care which and there is not a system AEC (echoCancellerPref == "auto" && !hasNativeAEC) // user specifically wants audioProcessor or (echoCancellerPref == "audioProcessor"); } // helper function static inline bool shouldUseAudioProcessorNoiseSuppression(bool hasNativeNS, const std::string& noiseSuppressionPref) { return // user doesn't care which and there is no system noise suppression (noiseSuppressionPref == "auto" && !hasNativeNS) // user specifically wants audioProcessor or (noiseSuppressionPref == "audioProcessor"); } void AudioLayer::setHasNativeAEC(bool hasNativeAEC) { JAMI_INFO("[audiolayer] setHasNativeAEC: %d", hasNativeAEC); std::lock_guard lock(audioProcessorMutex); hasNativeAEC_ = hasNativeAEC; // if we have a current audio processor, tell it to enable/disable its own AEC if (audioProcessor) { audioProcessor->enableEchoCancel( shouldUseAudioProcessorEchoCancel(hasNativeAEC, pref_.getEchoCanceller())); } } void AudioLayer::setHasNativeNS(bool hasNativeNS) { JAMI_INFO("[audiolayer] setHasNativeNS: %d", hasNativeNS); std::lock_guard lock(audioProcessorMutex); hasNativeNS_ = hasNativeNS; // if we have a current audio processor, tell it to enable/disable its own noise suppression if (audioProcessor) { audioProcessor->enableNoiseSuppression( shouldUseAudioProcessorNoiseSuppression(hasNativeNS, pref_.getNoiseReduce())); } } // must acquire lock beforehand void AudioLayer::createAudioProcessor() { auto nb_channels = std::max(audioFormat_.nb_channels, audioInputFormat_.nb_channels); auto sample_rate = std::max(audioFormat_.sample_rate, audioInputFormat_.sample_rate); sample_rate = std::clamp(sample_rate, 16000u, 48000u); AudioFormat formatForProcessor {sample_rate, nb_channels}; unsigned int frame_size; if (pref_.getAudioProcessor() == "speex") { // TODO: maybe force this to be equivalent to 20ms? as expected by speex frame_size = sample_rate / 50u; } else { frame_size = sample_rate / 100u; } JAMI_WARNING("Input {}", audioInputFormat_.toString()); JAMI_WARNING("Output {}", audioFormat_.toString()); JAMI_WARNING("Starting audio processor with: [{} Hz, {} channels, {} samples/frame]", sample_rate, nb_channels, frame_size); if (pref_.getAudioProcessor() == "webrtc") { #if HAVE_WEBRTC_AP JAMI_WARN("[audiolayer] using WebRTCAudioProcessor"); audioProcessor.reset(new WebRTCAudioProcessor(formatForProcessor, frame_size)); #else JAMI_ERR("[audiolayer] audioProcessor preference is webrtc, but library not linked! " "using null AudioProcessor instead"); audioProcessor.reset(); #endif } else if (pref_.getAudioProcessor() == "speex") { #if HAVE_SPEEXDSP JAMI_WARN("[audiolayer] using SpeexAudioProcessor"); audioProcessor.reset(new SpeexAudioProcessor(formatForProcessor, frame_size)); #else JAMI_ERR("[audiolayer] audioProcessor preference is speex, but library not linked! " "using null AudioProcessor instead"); audioProcessor.reset(); #endif } else if (pref_.getAudioProcessor() == "null") { JAMI_WARN("[audiolayer] using null AudioProcessor"); audioProcessor.reset(); } else { JAMI_ERR("[audiolayer] audioProcessor preference not recognized, using null AudioProcessor " "instead"); audioProcessor.reset(); } if (audioProcessor) { audioProcessor->enableNoiseSuppression( shouldUseAudioProcessorNoiseSuppression(hasNativeNS_, pref_.getNoiseReduce())); audioProcessor->enableAutomaticGainControl(pref_.isAGCEnabled()); audioProcessor->enableEchoCancel( shouldUseAudioProcessorEchoCancel(hasNativeAEC_, pref_.getEchoCanceller())); audioProcessor->enableVoiceActivityDetection(pref_.getVadEnabled()); } } // must acquire lock beforehand void AudioLayer::destroyAudioProcessor() { // delete it audioProcessor.reset(); } void AudioLayer::putUrgent(std::shared_ptr<AudioFrame> buffer) { urgentRingBuffer_.put(std::move(buffer)); } // Notify (with a beep) an incoming call when there is already a call in progress void AudioLayer::notifyIncomingCall() { if (not playIncomingCallBeep_) return; auto now = std::chrono::system_clock::now(); // Notify maximum once every 5 seconds if (now < lastNotificationTime_ + std::chrono::seconds(5)) return; lastNotificationTime_ = now; Tone tone("440/160", getSampleRate(), audioFormat_.sampleFormat); size_t nbSample = tone.getSize(); /* Put the data in the urgent ring buffer */ urgentRingBuffer_.flushAll(); urgentRingBuffer_.put(tone.getNext(nbSample)); } std::shared_ptr<AudioFrame> AudioLayer::getToRing(AudioFormat format, size_t writableSamples) { if (auto fileToPlay = Manager::instance().getTelephoneFile()) { auto fileformat = fileToPlay->getFormat(); bool resample = format != fileformat; size_t readableSamples = resample ? (rational<size_t>(writableSamples, format.sample_rate) * (size_t) fileformat.sample_rate) .real<size_t>() : writableSamples; return resampler_->resample(fileToPlay->getNext(readableSamples, isRingtoneMuted_), format); } return {}; } std::shared_ptr<AudioFrame> AudioLayer::getToPlay(AudioFormat format, size_t writableSamples) { notifyIncomingCall(); auto& bufferPool = Manager::instance().getRingBufferPool(); if (not playbackQueue_) playbackQueue_.reset(new AudioFrameResizer(format, writableSamples)); else playbackQueue_->setFrameSize(writableSamples); std::shared_ptr<AudioFrame> playbackBuf {}; while (!(playbackBuf = playbackQueue_->dequeue())) { std::shared_ptr<AudioFrame> resampled; if (auto urgentSamples = urgentRingBuffer_.get(RingBufferPool::DEFAULT_ID)) { bufferPool.discard(1, RingBufferPool::DEFAULT_ID); resampled = resampler_->resample(std::move(urgentSamples), format); } else if (auto toneToPlay = Manager::instance().getTelephoneTone()) { resampled = resampler_->resample(toneToPlay->getNext(), format); } else if (auto buf = bufferPool.getData(RingBufferPool::DEFAULT_ID)) { resampled = resampler_->resample(std::move(buf), format); } else { std::lock_guard lock(audioProcessorMutex); if (audioProcessor) { auto silence = std::make_shared<AudioFrame>(format, writableSamples); libav_utils::fillWithSilence(silence->pointer()); audioProcessor->putPlayback(silence); } break; } if (resampled) { std::lock_guard lock(audioProcessorMutex); if (audioProcessor) { audioProcessor->putPlayback(resampled); } playbackQueue_->enqueue(std::move(resampled)); } else break; } jami_tracepoint(audio_layer_get_to_play_end); return playbackBuf; } void AudioLayer::putRecorded(std::shared_ptr<AudioFrame>&& frame) { std::lock_guard lock(audioProcessorMutex); if (audioProcessor && playbackStarted_ && recordStarted_) { audioProcessor->putRecorded(std::move(frame)); while (auto rec = audioProcessor->getProcessed()) { mainRingBuffer_->put(std::move(rec)); } } else { mainRingBuffer_->put(std::move(frame)); } jami_tracepoint(audio_layer_put_recorded_end, ); } } // namespace jami
11,578
C++
.cpp
308
31.899351
108
0.694385
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,768
audioloop.cpp
savoirfairelinux_jami-daemon/src/media/audio/audioloop.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * Inspired by ringbuffer of Audacity Project * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "audioloop.h" #include "logger.h" #include "libav_deps.h" #include <algorithm> // std::min namespace jami { AudioLoop::AudioLoop(AudioFormat format) : format_(format) , buffer_(av_frame_alloc()) , pos_(0) { } AudioLoop::~AudioLoop() {} void AudioLoop::seek(double relative_position) { pos_ = static_cast<double>(getSize() * relative_position * 0.01); } void AudioLoop::getNext(AVFrame* output, bool mute) { if (!buffer_) { JAMI_ERR("buffer is NULL"); return; } const size_t buf_samples = buffer_->nb_samples; size_t pos = pos_; size_t total_samples = output->nb_samples; size_t output_pos = 0; if (buf_samples == 0) { JAMI_ERR("Audio loop size is 0"); av_samples_set_silence(output->data, 0, output->nb_samples, format_.nb_channels, format_.sampleFormat); return; } else if (pos >= buf_samples) { JAMI_ERR("Invalid loop position %zu", pos); return; } while (total_samples != 0) { size_t samples = std::min(total_samples, buf_samples - pos); if (not mute) av_samples_copy(output->data, buffer_->data, output_pos, pos, samples, format_.nb_channels, format_.sampleFormat); else av_samples_set_silence(output->data, output_pos, samples, format_.nb_channels, format_.sampleFormat); output_pos += samples; pos = (pos + samples) % buf_samples; total_samples -= samples; } pos_ = pos; onBufferFinish(); } void AudioLoop::onBufferFinish() {} std::unique_ptr<AudioFrame> AudioLoop::getNext(size_t samples, bool mute) { if (samples == 0) { samples = buffer_->sample_rate / 50; } auto buffer = std::make_unique<AudioFrame>(format_, samples); getNext(buffer->pointer(), mute); return buffer; } } // namespace jami
2,760
C++
.cpp
87
27.758621
126
0.676448
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,769
audio_sender.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio_sender.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audio_sender.h" #include "client/videomanager.h" #include "libav_deps.h" #include "logger.h" #include "media_encoder.h" #include "media_io_handle.h" #include "media_stream.h" #include "resampler.h" #include <memory> namespace jami { AudioSender::AudioSender(const std::string& dest, const MediaDescription& args, SocketPair& socketPair, const uint16_t seqVal, const uint16_t mtu) : dest_(dest) , args_(args) , seqVal_(seqVal) , mtu_(mtu) { setup(socketPair); } AudioSender::~AudioSender() { audioEncoder_.reset(); muxContext_.reset(); } bool AudioSender::setup(SocketPair& socketPair) { audioEncoder_.reset(new MediaEncoder); muxContext_.reset(socketPair.createIOContext(mtu_)); try { /* Encoder setup */ JAMI_DBG("audioEncoder_->openOutput %s", dest_.c_str()); audioEncoder_->openOutput(dest_, "rtp"); audioEncoder_->setOptions(args_); auto codec = std::static_pointer_cast<SystemAudioCodecInfo>(args_.codec); auto ms = MediaStream("audio sender", codec->audioformat); audioEncoder_->setOptions(ms); audioEncoder_->addStream(*args_.codec); audioEncoder_->setInitSeqVal(seqVal_); audioEncoder_->setIOContext(muxContext_->getContext()); } catch (const MediaEncoderException& e) { JAMI_ERR("%s", e.what()); return false; } #ifdef DEBUG_SDP audioEncoder_->print_sdp(); #endif return true; } void AudioSender::update(Observable<std::shared_ptr<jami::MediaFrame>>* /*obs*/, const std::shared_ptr<jami::MediaFrame>& framePtr) { auto frame = framePtr->pointer(); frame->pts = sent_samples; sent_samples += frame->nb_samples; // check for change in voice activity, if so, call callback // downcast MediaFrame to AudioFrame bool hasVoice = std::dynamic_pointer_cast<AudioFrame>(framePtr)->has_voice; if (hasVoice != voice_) { voice_ = hasVoice; if (voiceCallback_) { voiceCallback_(voice_); } else { JAMI_ERR("AudioSender no voice callback!"); } } if (audioEncoder_->encodeAudio(*std::static_pointer_cast<AudioFrame>(framePtr)) < 0) JAMI_ERR("encoding failed"); } void AudioSender::setVoiceCallback(std::function<void(bool)> cb) { if (cb) { voiceCallback_ = std::move(cb); } else { JAMI_ERR("AudioSender attempting to set invalid voice callback"); } } uint16_t AudioSender::getLastSeqValue() { return audioEncoder_->getLastSeqValue(); } int AudioSender::setPacketLoss(uint64_t pl) { // The encoder may be destroy during a bitrate change // when a codec parameter like auto quality change if (!audioEncoder_) return -1; // NOK return audioEncoder_->setPacketLoss(pl); } } // namespace jami
3,651
C++
.cpp
113
27.247788
88
0.668654
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,770
ringbuffer.cpp
savoirfairelinux_jami-daemon/src/media/audio/ringbuffer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ringbuffer.h" #include "logger.h" #include "client/ring_signal.h" #include "media_buffer.h" #include "libav_deps.h" #include <chrono> #include <cstdlib> #include <cstring> #include <algorithm> namespace jami { // corresponds to 160 ms (about 5 rtp packets) static const size_t MIN_BUFFER_SIZE = 1024; static constexpr const int RMS_SIGNAL_INTERVAL = 5; RingBuffer::RingBuffer(const std::string& rbuf_id, size_t /*size*/, AudioFormat format) : id(rbuf_id) , endPos_(0) , format_(format) , lock_() , not_empty_() , readoffsets_() , resizer_(format_, format_.sample_rate / 50, [this](std::shared_ptr<AudioFrame>&& frame) { putToBuffer(std::move(frame)); }) { JAMI_LOG("Create new RingBuffer {}", id); } RingBuffer::~RingBuffer() { JAMI_LOG("Destroy RingBuffer {}", id); } void RingBuffer::flush(const std::string& ringbufferId) { storeReadOffset(endPos_, ringbufferId); } void RingBuffer::flushAll() { for (auto& offset : readoffsets_) offset.second.offset = endPos_; } size_t RingBuffer::putLength() const { const size_t buffer_size = buffer_.size(); if (buffer_size == 0) return 0; const size_t startPos = getSmallestReadOffset(); return (endPos_ + buffer_size - startPos) % buffer_size; } size_t RingBuffer::getLength(const std::string& ringbufferId) const { const size_t buffer_size = buffer_.size(); if (buffer_size == 0) return 0; return (endPos_ + buffer_size - getReadOffset(ringbufferId)) % buffer_size; } void RingBuffer::debug() { JAMI_DBG("Start=%zu; End=%zu; BufferSize=%zu", getSmallestReadOffset(), endPos_, buffer_.size()); } size_t RingBuffer::getReadOffset(const std::string& ringbufferId) const { auto iter = readoffsets_.find(ringbufferId); return (iter != readoffsets_.end()) ? iter->second.offset : 0; } size_t RingBuffer::getSmallestReadOffset() const { if (hasNoReadOffsets()) return 0; size_t smallest = buffer_.size(); for (auto const& iter : readoffsets_) smallest = std::min(smallest, iter.second.offset); return smallest; } void RingBuffer::storeReadOffset(size_t offset, const std::string& ringbufferId) { ReadOffsetMap::iterator iter = readoffsets_.find(ringbufferId); if (iter != readoffsets_.end()) iter->second.offset = offset; else JAMI_ERROR("RingBuffer::storeReadOffset() failed: unknown ringbuffer '{}'", ringbufferId); } void RingBuffer::createReadOffset(const std::string& ringbufferId) { std::lock_guard l(lock_); if (!hasThisReadOffset(ringbufferId)) readoffsets_.emplace(ringbufferId, ReadOffset {endPos_, {}}); } void RingBuffer::removeReadOffset(const std::string& ringbufferId) { std::lock_guard l(lock_); auto iter = readoffsets_.find(ringbufferId); if (iter != readoffsets_.end()) readoffsets_.erase(iter); } bool RingBuffer::hasThisReadOffset(const std::string& ringbufferId) const { return readoffsets_.find(ringbufferId) != readoffsets_.end(); } bool RingBuffer::hasNoReadOffsets() const { return readoffsets_.empty(); } // // For the writer only: // void RingBuffer::put(std::shared_ptr<AudioFrame>&& data) { std::lock_guard l(writeLock_); resizer_.enqueue(resampler_.resample(std::move(data), format_)); } // This one puts some data inside the ring buffer. void RingBuffer::putToBuffer(std::shared_ptr<AudioFrame>&& data) { std::lock_guard l(lock_); const size_t buffer_size = buffer_.size(); if (buffer_size == 0) return; size_t len = buffer_size - putLength(); if (len == 0) discard(1); size_t pos = endPos_; buffer_[pos] = std::move(data); const auto& newBuf = buffer_[pos]; pos = (pos + 1) % buffer_size; endPos_ = pos; if (rmsSignal_) { ++rmsFrameCount_; rmsLevel_ += newBuf->calcRMS(); if (rmsFrameCount_ == RMS_SIGNAL_INTERVAL) { emitSignal<libjami::AudioSignal::AudioMeter>(id, rmsLevel_ / RMS_SIGNAL_INTERVAL); rmsLevel_ = 0; rmsFrameCount_ = 0; } } for (auto& offset : readoffsets_) { if (offset.second.callback) offset.second.callback(newBuf); } not_empty_.notify_all(); } // // For the reader only: // size_t RingBuffer::availableForGet(const std::string& ringbufferId) const { // Used space return getLength(ringbufferId); } std::shared_ptr<AudioFrame> RingBuffer::get(const std::string& ringbufferId) { std::lock_guard l(lock_); auto offset = readoffsets_.find(ringbufferId); if (offset == readoffsets_.end()) return {}; const size_t buffer_size = buffer_.size(); if (buffer_size == 0) return {}; size_t startPos = offset->second.offset; size_t len = (endPos_ + buffer_size - startPos) % buffer_size; if (len == 0) return {}; auto ret = buffer_[startPos]; offset->second.offset = (startPos + 1) % buffer_size; return ret; } size_t RingBuffer::waitForDataAvailable(const std::string& ringbufferId, const time_point& deadline) const { std::unique_lock l(lock_); if (buffer_.empty()) return 0; if (readoffsets_.find(ringbufferId) == readoffsets_.end()) return 0; size_t getl = 0; auto check = [=, &getl] { // Re-find read_ptr: it may be destroyed during the wait const size_t buffer_size = buffer_.size(); const auto read_ptr = readoffsets_.find(ringbufferId); if (buffer_size == 0 || read_ptr == readoffsets_.end()) return true; getl = (endPos_ + buffer_size - read_ptr->second.offset) % buffer_size; return getl != 0; }; if (deadline == time_point::max()) { // no timeout provided, wait as long as necessary not_empty_.wait(l, check); } else { not_empty_.wait_until(l, deadline, check); } return getl; } size_t RingBuffer::discard(size_t toDiscard, const std::string& ringbufferId) { std::lock_guard l(lock_); const size_t buffer_size = buffer_.size(); if (buffer_size == 0) return 0; auto offset = readoffsets_.find(ringbufferId); if (offset == readoffsets_.end()) return 0; size_t len = (endPos_ + buffer_size - offset->second.offset) % buffer_size; toDiscard = std::min(toDiscard, len); offset->second.offset = (offset->second.offset + toDiscard) % buffer_size; return toDiscard; } size_t RingBuffer::discard(size_t toDiscard) { const size_t buffer_size = buffer_.size(); if (buffer_size == 0) return 0; for (auto& r : readoffsets_) { size_t dst = (r.second.offset + buffer_size - endPos_) % buffer_size; if (dst < toDiscard) r.second.offset = (r.second.offset + toDiscard - dst) % buffer_size; } return toDiscard; } } // namespace jami
7,600
C++
.cpp
251
26.151394
101
0.667352
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,771
audio_rtp_session.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio_rtp_session.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "libav_deps.h" // MUST BE INCLUDED FIRST #include "audio_rtp_session.h" #include "logger.h" #include "noncopyable.h" #include "sip/sdp.h" #include "audio_receive_thread.h" #include "audio_sender.h" #include "socket_pair.h" #include "media_recorder.h" #include "media_encoder.h" #include "media_decoder.h" #include "media_io_handle.h" #include "media_device.h" #include "media_const.h" #include "audio/audio_input.h" #include "audio/ringbufferpool.h" #include "audio/resampler.h" #include "client/videomanager.h" #include "manager.h" #include "observer.h" #include <asio/io_context.hpp> #include <sstream> namespace jami { AudioRtpSession::AudioRtpSession(const std::string& callId, const std::string& streamId, const std::shared_ptr<MediaRecorder>& rec) : RtpSession(callId, streamId, MediaType::MEDIA_AUDIO) , rtcpCheckerThread_([] { return true; }, [this] { processRtcpChecker(); }, [] {}) { recorder_ = rec; JAMI_DEBUG("Created Audio RTP session: {} - stream id {}", fmt::ptr(this), streamId_); // don't move this into the initializer list or Cthulus will emerge ringbuffer_ = Manager::instance().getRingBufferPool().createRingBuffer(streamId_); } AudioRtpSession::~AudioRtpSession() { deinitRecorder(); stop(); JAMI_DEBUG("Destroyed Audio RTP session: {} - stream id {}", fmt::ptr(this), streamId_); } void AudioRtpSession::startSender() { std::lock_guard lock(mutex_); JAMI_DEBUG("Start audio RTP sender: input [{}] - muted [{}]", input_, muteState_ ? "YES" : "NO"); if (not send_.enabled or send_.onHold) { JAMI_WARNING("Audio sending disabled"); if (sender_) { if (socketPair_) socketPair_->interrupt(); if (audioInput_) audioInput_->detach(sender_.get()); sender_.reset(); } return; } if (sender_) JAMI_WARNING("Restarting audio sender"); if (audioInput_) audioInput_->detach(sender_.get()); bool fileAudio = !input_.empty() && input_.find("file://") != std::string::npos; auto audioInputId = streamId_; if (fileAudio) { auto suffix = input_; static const std::string& sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = input_.find(sep); if (pos != std::string::npos) { suffix = input_.substr(pos + sep.size()); } audioInputId = suffix; } // sender sets up input correctly, we just keep a reference in case startSender is called audioInput_ = jami::getAudioInput(audioInputId); audioInput_->setRecorderCallback( [w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachLocalRecorder(ms); }); }); audioInput_->setMuted(muteState_); audioInput_->setSuccessfulSetupCb(onSuccessfulSetup_); if (!fileAudio) { auto newParams = audioInput_->switchInput(input_); try { if (newParams.valid() && newParams.wait_for(NEWPARAMS_TIMEOUT) == std::future_status::ready) { localAudioParams_ = newParams.get(); } else { JAMI_ERROR("No valid new audio parameters"); return; } } catch (const std::exception& e) { JAMI_ERROR("Exception while retrieving audio parameters: {}", e.what()); return; } } if (streamId_ != audioInput_->getId()) Manager::instance().getRingBufferPool().bindHalfDuplexOut(streamId_, audioInput_->getId()); send_.fecEnabled = true; // be sure to not send any packets before saving last RTP seq value socketPair_->stopSendOp(); if (sender_) initSeqVal_ = sender_->getLastSeqValue() + 1; try { sender_.reset(); socketPair_->stopSendOp(false); sender_.reset(new AudioSender(getRemoteRtpUri(), send_, *socketPair_, initSeqVal_, mtu_)); } catch (const MediaEncoderException& e) { JAMI_ERROR("{}", e.what()); send_.enabled = false; } if (voiceCallback_) sender_->setVoiceCallback(voiceCallback_); // NOTE do after sender/encoder are ready auto codec = std::static_pointer_cast<SystemAudioCodecInfo>(send_.codec); audioInput_->setFormat(codec->audioformat); audioInput_->attach(sender_.get()); if (not rtcpCheckerThread_.isRunning()) rtcpCheckerThread_.start(); } void AudioRtpSession::restartSender() { std::lock_guard lock(mutex_); // ensure that start has been called before restart if (not socketPair_) { return; } startSender(); } void AudioRtpSession::startReceiver() { if (socketPair_) socketPair_->setReadBlockingMode(true); if (not receive_.enabled or receive_.onHold) { JAMI_WARNING("Audio receiving disabled"); receiveThread_.reset(); return; } if (receiveThread_) JAMI_WARNING("Restarting audio receiver"); auto accountAudioCodec = std::static_pointer_cast<SystemAudioCodecInfo>(receive_.codec); receiveThread_.reset(new AudioReceiveThread(streamId_, accountAudioCodec->audioformat, receive_.receiving_sdp, mtu_)); receiveThread_->setRecorderCallback([w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachRemoteRecorder(ms); }); }); receiveThread_->addIOContext(*socketPair_); receiveThread_->setSuccessfulSetupCb(onSuccessfulSetup_); receiveThread_->startReceiver(); } void AudioRtpSession::start(std::unique_ptr<dhtnet::IceSocket> rtp_sock, std::unique_ptr<dhtnet::IceSocket> rtcp_sock) { std::lock_guard lock(mutex_); if (not send_.enabled and not receive_.enabled) { stop(); return; } try { if (rtp_sock and rtcp_sock) { if (send_.addr) { rtp_sock->setDefaultRemoteAddress(send_.addr); } auto& rtcpAddr = send_.rtcp_addr ? send_.rtcp_addr : send_.addr; if (rtcpAddr) { rtcp_sock->setDefaultRemoteAddress(rtcpAddr); } socketPair_.reset(new SocketPair(std::move(rtp_sock), std::move(rtcp_sock))); } else { socketPair_.reset(new SocketPair(getRemoteRtpUri().c_str(), receive_.addr.getPort())); } if (send_.crypto and receive_.crypto) { socketPair_->createSRTP(receive_.crypto.getCryptoSuite().c_str(), receive_.crypto.getSrtpKeyInfo().c_str(), send_.crypto.getCryptoSuite().c_str(), send_.crypto.getSrtpKeyInfo().c_str()); } } catch (const std::runtime_error& e) { JAMI_ERROR("Socket creation failed: {}", e.what()); return; } startSender(); startReceiver(); } void AudioRtpSession::stop() { std::lock_guard lock(mutex_); JAMI_DEBUG("[{}] Stopping receiver", fmt::ptr(this)); if (not receiveThread_) return; if (socketPair_) socketPair_->setReadBlockingMode(false); receiveThread_->stopReceiver(); if (audioInput_) audioInput_->detach(sender_.get()); if (socketPair_) socketPair_->interrupt(); rtcpCheckerThread_.join(); receiveThread_.reset(); sender_.reset(); socketPair_.reset(); audioInput_.reset(); } void AudioRtpSession::setMuted(bool muted, Direction dir) { Manager::instance().ioContext()->post([w=weak_from_this(), muted, dir]() { if (auto shared = w.lock()) { std::lock_guard lock(shared->mutex_); if (dir == Direction::SEND) { shared->muteState_ = muted; if (shared->audioInput_) { shared->audioInput_->setMuted(muted); } } else { if (shared->receiveThread_) { auto ms = shared->receiveThread_->getInfo(); ms.name = shared->streamId_ + ":remote"; if (muted) { if (auto ob = shared->recorder_->getStream(ms.name)) { shared->receiveThread_->detach(ob); shared->recorder_->removeStream(ms); } } else { if (auto ob = shared->recorder_->addStream(ms)) { shared->receiveThread_->attach(ob); } } } } } }); } void AudioRtpSession::setVoiceCallback(std::function<void(bool)> cb) { std::lock_guard lock(mutex_); voiceCallback_ = std::move(cb); if (sender_) { sender_->setVoiceCallback(voiceCallback_); } } bool AudioRtpSession::check_RCTP_Info_RR(RTCPInfo& rtcpi) { auto rtcpInfoVect = socketPair_->getRtcpRR(); unsigned totalLost = 0; unsigned totalJitter = 0; unsigned nbDropNotNull = 0; auto vectSize = rtcpInfoVect.size(); if (vectSize != 0) { for (const auto& it : rtcpInfoVect) { if (it.fraction_lost != 0) // Exclude null drop nbDropNotNull++; totalLost += it.fraction_lost; totalJitter += ntohl(it.jitter); } rtcpi.packetLoss = nbDropNotNull ? (float) (100 * totalLost) / (256.0 * nbDropNotNull) : 0; // Jitter is expressed in timestamp unit -> convert to milliseconds // https://stackoverflow.com/questions/51956520/convert-jitter-from-rtp-timestamp-unit-to-millisseconds rtcpi.jitter = (totalJitter / vectSize / 90000.0f) * 1000; rtcpi.nb_sample = vectSize; rtcpi.latency = socketPair_->getLastLatency(); return true; } return false; } void AudioRtpSession::adaptQualityAndBitrate() { RTCPInfo rtcpi {}; if (check_RCTP_Info_RR(rtcpi)) { dropProcessing(&rtcpi); } } void AudioRtpSession::dropProcessing(RTCPInfo* rtcpi) { auto pondLoss = getPonderateLoss(rtcpi->packetLoss); setNewPacketLoss(pondLoss); } void AudioRtpSession::setNewPacketLoss(unsigned int newPL) { newPL = std::clamp((int) newPL, 0, 100); if (newPL != packetLoss_) { if (sender_) { auto ret = sender_->setPacketLoss(newPL); packetLoss_ = newPL; if (ret == -1) JAMI_ERROR("Fail to access the encoder"); } else { JAMI_ERROR("Fail to access the sender"); } } } float AudioRtpSession::getPonderateLoss(float lastLoss) { static float pond = 10.0f; pond = floor(0.5 * lastLoss + 0.5 * pond); if (lastLoss > pond) { return lastLoss; } else { return pond; } } void AudioRtpSession::processRtcpChecker() { adaptQualityAndBitrate(); socketPair_->waitForRTCP(std::chrono::seconds(rtcp_checking_interval)); } void AudioRtpSession::attachRemoteRecorder(const MediaStream& ms) { std::lock_guard lock(mutex_); if (!recorder_ || !receiveThread_) return; MediaStream remoteMS = ms; remoteMS.name = streamId_ + ":remote"; if (auto ob = recorder_->addStream(remoteMS)) { receiveThread_->attach(ob); } } void AudioRtpSession::attachLocalRecorder(const MediaStream& ms) { std::lock_guard lock(mutex_); if (!recorder_ || !audioInput_) return; MediaStream localMS = ms; localMS.name = streamId_ + ":local"; if (auto ob = recorder_->addStream(localMS)) { audioInput_->attach(ob); } } void AudioRtpSession::initRecorder() { if (!recorder_) return; if (receiveThread_) receiveThread_->setRecorderCallback( [w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachRemoteRecorder(ms); }); }); if (audioInput_) audioInput_->setRecorderCallback( [w=weak_from_this()](const MediaStream& ms) { Manager::instance().ioContext()->post([w=std::move(w), ms]() { if (auto shared = w.lock()) shared->attachLocalRecorder(ms); }); }); } void AudioRtpSession::deinitRecorder() { if (!recorder_) return; if (receiveThread_) { auto ms = receiveThread_->getInfo(); ms.name = streamId_ + ":remote"; if (auto ob = recorder_->getStream(ms.name)) { receiveThread_->detach(ob); recorder_->removeStream(ms); } } if (audioInput_) { auto ms = audioInput_->getInfo(); ms.name = streamId_ + ":local"; if (auto ob = recorder_->getStream(ms.name)) { audioInput_->detach(ob); recorder_->removeStream(ms); } } } } // namespace jami
14,086
C++
.cpp
409
26.589242
113
0.596196
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,772
audio_receive_thread.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio_receive_thread.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audio_receive_thread.h" #include "libav_deps.h" #include "logger.h" #include "manager.h" #include "media_decoder.h" #include "media_io_handle.h" #include "media_recorder.h" #include "ringbuffer.h" #include "ringbufferpool.h" #include <memory> namespace jami { AudioReceiveThread::AudioReceiveThread(const std::string& streamId, const AudioFormat& format, const std::string& sdp, const uint16_t mtu) : streamId_(streamId) , format_(format) , stream_(sdp) , sdpContext_(new MediaIOHandle(sdp.size(), false, &readFunction, 0, 0, this)) , mtu_(mtu) , loop_(std::bind(&AudioReceiveThread::setup, this), std::bind(&AudioReceiveThread::process, this), std::bind(&AudioReceiveThread::cleanup, this)) {} AudioReceiveThread::~AudioReceiveThread() { loop_.join(); } bool AudioReceiveThread::setup() { std::lock_guard lk(mutex_); audioDecoder_.reset(new MediaDecoder([this](std::shared_ptr<MediaFrame>&& frame) mutable { notify(frame); ringbuffer_->put(std::static_pointer_cast<AudioFrame>(frame)); })); audioDecoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); audioDecoder_->setInterruptCallback(interruptCb, this); // custom_io so the SDP demuxer will not open any UDP connections args_.input = SDP_FILENAME; args_.format = "sdp"; args_.sdp_flags = "custom_io"; if (stream_.str().empty()) { JAMI_ERR("No SDP loaded"); return false; } audioDecoder_->setIOContext(sdpContext_.get()); audioDecoder_->setFEC(true); if (audioDecoder_->openInput(args_)) { JAMI_ERR("Unable to open input \"%s\"", SDP_FILENAME); return false; } // Now replace our custom AVIOContext with one that will read packets audioDecoder_->setIOContext(demuxContext_.get()); if (audioDecoder_->setupAudio()) { JAMI_ERR("decoder IO startup failed"); return false; } ringbuffer_ = Manager::instance().getRingBufferPool().createRingBuffer(streamId_); if (onSuccessfulSetup_) onSuccessfulSetup_(MEDIA_AUDIO, 1); return true; } void AudioReceiveThread::process() { audioDecoder_->decode(); } void AudioReceiveThread::cleanup() { std::lock_guard lk(mutex_); audioDecoder_.reset(); demuxContext_.reset(); } int AudioReceiveThread::readFunction(void* opaque, uint8_t* buf, int buf_size) { std::istream& is = static_cast<AudioReceiveThread*>(opaque)->stream_; is.read(reinterpret_cast<char*>(buf), buf_size); auto count = is.gcount(); return count ? count : AVERROR_EOF; } // This callback is used by libav internally to break out of blocking calls int AudioReceiveThread::interruptCb(void* data) { auto context = static_cast<AudioReceiveThread*>(data); return not context->loop_.isRunning(); } void AudioReceiveThread::addIOContext(SocketPair& socketPair) { demuxContext_.reset(socketPair.createIOContext(mtu_)); } void AudioReceiveThread::setRecorderCallback( const std::function<void(const MediaStream& ms)>& cb) { recorderCallback_ = cb; if (audioDecoder_) audioDecoder_->setContextCallback([this]() { if (recorderCallback_) recorderCallback_(getInfo()); }); } MediaStream AudioReceiveThread::getInfo() const { if (!audioDecoder_) return {}; return audioDecoder_->getStream("a:remote"); } void AudioReceiveThread::startReceiver() { loop_.start(); } void AudioReceiveThread::stopReceiver() { loop_.stop(); } }; // namespace jami
4,452
C++
.cpp
143
26.524476
94
0.68238
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,773
audio_frame_resizer.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio_frame_resizer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audio_frame_resizer.h" #include "libav_deps.h" #include "logger.h" extern "C" { #include <libavutil/audio_fifo.h> } #include <stdexcept> namespace jami { AudioFrameResizer::AudioFrameResizer(const AudioFormat& format, int size, std::function<void(std::shared_ptr<AudioFrame>&&)> cb) : format_(format) , frameSize_(size) , cb_(cb) , queue_(av_audio_fifo_alloc(format.sampleFormat, format.nb_channels, frameSize_)) {} AudioFrameResizer::~AudioFrameResizer() { av_audio_fifo_free(queue_); } int AudioFrameResizer::samples() const { return av_audio_fifo_size(queue_); } int AudioFrameResizer::frameSize() const { return frameSize_; } AudioFormat AudioFrameResizer::format() const { return format_; } void AudioFrameResizer::setFormat(const AudioFormat& format, int size) { if (size) setFrameSize(size); if (format != format_) { if (auto discarded = samples()) JAMI_WARN("Discarding %d samples", discarded); av_audio_fifo_free(queue_); format_ = format; queue_ = av_audio_fifo_alloc(format.sampleFormat, format.nb_channels, frameSize_); } } void AudioFrameResizer::setFrameSize(int frameSize) { if (frameSize_ != frameSize) { frameSize_ = frameSize; if (cb_) while (auto frame = dequeue()) cb_(std::move(frame)); } } void AudioFrameResizer::enqueue(std::shared_ptr<AudioFrame>&& frame) { if (not frame or frame->pointer() == nullptr) return; int ret = 0; auto f = frame->pointer(); AudioFormat format(f->sample_rate, f->ch_layout.nb_channels, (AVSampleFormat) f->format); if (format != format_) { JAMI_WARNING("Expected {} but got {}", format_.toString(), format.toString()); setFormat(format, frameSize_); } auto nb_samples = samples(); if (cb_ && nb_samples == 0 && f->nb_samples == frameSize_) { nextOutputPts_ = frame->pointer()->pts + frameSize_; cb_(std::move(frame)); return; // return if frame was just passed through } // voice activity hasVoice_ = frame->has_voice; // queue reallocates itself if need be if ((ret = av_audio_fifo_write(queue_, reinterpret_cast<void**>(f->data), f->nb_samples)) < 0) { JAMI_ERR() << "Audio resizer error: " << libav_utils::getError(ret); throw std::runtime_error("Failed to add audio to frame resizer"); } if (nextOutputPts_ == 0) nextOutputPts_ = frame->pointer()->pts - nb_samples; if (cb_) while (auto frame = dequeue()) cb_(std::move(frame)); } std::shared_ptr<AudioFrame> AudioFrameResizer::dequeue() { if (samples() < frameSize_) return {}; auto frame = std::make_shared<AudioFrame>(format_, frameSize_); int ret; if ((ret = av_audio_fifo_read(queue_, reinterpret_cast<void**>(frame->pointer()->data), frameSize_)) < 0) { JAMI_ERR() << "Unable to read samples from queue: " << libav_utils::getError(ret); return {}; } frame->pointer()->pts = nextOutputPts_; frame->has_voice = hasVoice_; nextOutputPts_ += frameSize_; return frame; } } // namespace jami
4,060
C++
.cpp
125
27.08
100
0.638477
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,774
jacklayer.cpp
savoirfairelinux_jami-daemon/src/media/audio/jack/jacklayer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "jacklayer.h" #include "logger.h" #include "audio/resampler.h" #include "audio/ringbufferpool.h" #include "audio/ringbuffer.h" #include "audio/audioloop.h" #include "manager.h" #include <unistd.h> #include <cassert> #include <climits> /* TODO * implement shutdown callback * auto connect optional */ namespace jami { namespace { void connectPorts(jack_client_t* client, int portType, const std::vector<jack_port_t*>& ports) { const char** physical_ports = jack_get_ports(client, NULL, NULL, portType | JackPortIsPhysical); for (unsigned i = 0; physical_ports[i]; ++i) { if (i >= ports.size()) break; const char* port = jack_port_name(ports[i]); if (portType & JackPortIsInput) { if (jack_connect(client, port, physical_ports[i])) { JAMI_ERR("Unable to connect %s to %s", port, physical_ports[i]); break; } } else { if (jack_connect(client, physical_ports[i], port)) { JAMI_ERR("Unable to connect port %s to %s", physical_ports[i], port); break; } } } jack_free(physical_ports); } bool ringbuffer_ready_for_read(const jack_ringbuffer_t* rb) { // XXX 512 is arbitrary return jack_ringbuffer_read_space(rb) > 512; } } // namespace void JackLayer::playback() { notifyIncomingCall(); auto format = audioFormat_; format.sampleFormat = AV_SAMPLE_FMT_FLTP; if (auto toPlay = getPlayback(format, writeSpace())) { write(*toPlay); } } void JackLayer::capture() { if (auto buf = read()) mainRingBuffer_->put(std::move(buf)); } size_t JackLayer::writeSpace() { if (out_ringbuffers_.empty()) return 0; size_t toWrite {std::numeric_limits<size_t>::max()}; for (unsigned i = 0; i < out_ringbuffers_.size(); ++i) { toWrite = std::min(toWrite, jack_ringbuffer_write_space(out_ringbuffers_[i])); } return std::min<size_t>(toWrite / sizeof(float), audioFormat_.sample_rate / 25); } void JackLayer::write(const AudioFrame& buffer) { auto num_samples = buffer.pointer()->nb_samples; auto num_bytes = num_samples * sizeof(float); auto channels = std::min<size_t>(out_ringbuffers_.size(), buffer.pointer()->ch_layout.nb_channels); for (size_t i = 0; i < channels; ++i) { jack_ringbuffer_write(out_ringbuffers_[i], (const char*) buffer.pointer()->extended_data[i], num_bytes); } } std::unique_ptr<AudioFrame> JackLayer::read() { if (in_ringbuffers_.empty()) return {}; size_t toRead {std::numeric_limits<size_t>::max()}; for (unsigned i = 0; i < in_ringbuffers_.size(); ++i) { toRead = std::min(toRead, jack_ringbuffer_read_space(in_ringbuffers_[i])); } if (not toRead) return {}; auto format = audioInputFormat_; format.sampleFormat = AV_SAMPLE_FMT_FLTP; auto buffer = std::make_unique<AudioFrame>(format, toRead / sizeof(jack_default_audio_sample_t)); for (unsigned i = 0; i < in_ringbuffers_.size(); ++i) { jack_ringbuffer_read(in_ringbuffers_[i], (char*) buffer->pointer()->extended_data[i], toRead); } return buffer; } /* This thread can lock, do whatever it wants, and read from/write to the jack * ring buffers * XXX: Access to shared state (i.e. member variables) should be synchronized if needed */ void JackLayer::ringbuffer_worker() { flushMain(); flushUrgent(); while (true) { std::unique_lock lock(ringbuffer_thread_mutex_); // may have changed, we don't want to wait for a notification we won't get if (status_ != Status::Started) return; // FIXME this is all kinds of evil std::this_thread::sleep_for(std::chrono::milliseconds(20)); capture(); playback(); // wait until process() signals more data // FIXME: this checks for spurious wakes, but the predicate // is rather arbitrary. We should wait until ring has/needs data // and jack has/needs data. data_ready_.wait(lock, [&] { return status_ != Status::Started or ringbuffer_ready_for_read(in_ringbuffers_[0]); }); } } void createPorts(jack_client_t* client, std::vector<jack_port_t*>& ports, bool playback, std::vector<jack_ringbuffer_t*>& ringbuffers) { const char** physical_ports = jack_get_ports(client, NULL, NULL, playback ? JackPortIsInput : JackPortIsOutput | JackPortIsPhysical); for (unsigned i = 0; physical_ports[i]; ++i) { if (i == 2) break; char port_name[32] = {0}; if (playback) snprintf(port_name, sizeof(port_name), "out_%d", i + 1); else snprintf(port_name, sizeof(port_name), "in_%d", i + 1); port_name[sizeof(port_name) - 1] = '\0'; jack_port_t* port = jack_port_register(client, port_name, JACK_DEFAULT_AUDIO_TYPE, playback ? JackPortIsOutput : JackPortIsInput, 0); if (port == nullptr) throw std::runtime_error("Unable to register JACK output port"); ports.push_back(port); static const unsigned RB_SIZE = 16384; jack_ringbuffer_t* rb = jack_ringbuffer_create(RB_SIZE); if (rb == nullptr) throw std::runtime_error("Unable to create JACK ringbuffer"); if (jack_ringbuffer_mlock(rb)) throw std::runtime_error("Unable to lock JACK ringbuffer in memory"); ringbuffers.push_back(rb); } jack_free(physical_ports); } JackLayer::JackLayer(const AudioPreference& p) : AudioLayer(p) , captureClient_(nullptr) , playbackClient_(nullptr) { playbackClient_ = jack_client_open(PACKAGE_NAME, (jack_options_t)(JackNullOption | JackNoStartServer), NULL); if (!playbackClient_) throw std::runtime_error("Unable to open JACK client"); captureClient_ = jack_client_open(PACKAGE_NAME, (jack_options_t)(JackNullOption | JackNoStartServer), NULL); if (!captureClient_) throw std::runtime_error("Unable to open JACK client"); jack_set_process_callback(captureClient_, process_capture, this); jack_set_process_callback(playbackClient_, process_playback, this); createPorts(playbackClient_, out_ports_, true, out_ringbuffers_); createPorts(captureClient_, in_ports_, false, in_ringbuffers_); const auto playRate = jack_get_sample_rate(playbackClient_); const auto captureRate = jack_get_sample_rate(captureClient_); audioInputFormat_ = {captureRate, (unsigned) in_ringbuffers_.size()}; hardwareFormatAvailable(AudioFormat(playRate, out_ringbuffers_.size())); hardwareInputFormatAvailable(audioInputFormat_); jack_on_shutdown(playbackClient_, onShutdown, this); } JackLayer::~JackLayer() { stopStream(); for (auto p : out_ports_) jack_port_unregister(playbackClient_, p); for (auto p : in_ports_) jack_port_unregister(captureClient_, p); if (jack_client_close(playbackClient_)) JAMI_ERR("Unable to close JACK client"); if (jack_client_close(captureClient_)) JAMI_ERR("Unable to close JACK client"); for (auto r : out_ringbuffers_) jack_ringbuffer_free(r); for (auto r : in_ringbuffers_) jack_ringbuffer_free(r); } void JackLayer::updatePreference(AudioPreference& /*pref*/, int /*index*/, AudioDeviceType /*type*/) {} std::vector<std::string> JackLayer::getCaptureDeviceList() const { return std::vector<std::string>(); } std::vector<std::string> JackLayer::getPlaybackDeviceList() const { return std::vector<std::string>(); } int JackLayer::getAudioDeviceIndex(const std::string& /*name*/, AudioDeviceType /*type*/) const { return 0; } std::string JackLayer::getAudioDeviceName(int /*index*/, AudioDeviceType /*type*/) const { return ""; } int JackLayer::getIndexCapture() const { return 0; } int JackLayer::getIndexPlayback() const { return 0; } int JackLayer::getIndexRingtone() const { return 0; } int JackLayer::process_capture(jack_nframes_t frames, void* arg) { JackLayer* context = static_cast<JackLayer*>(arg); for (unsigned i = 0; i < context->in_ringbuffers_.size(); ++i) { // read from input jack_default_audio_sample_t* in_buffers = static_cast<jack_default_audio_sample_t*>( jack_port_get_buffer(context->in_ports_[i], frames)); const size_t bytes_to_read = frames * sizeof(*in_buffers); size_t bytes_to_rb = jack_ringbuffer_write(context->in_ringbuffers_[i], (char*) in_buffers, bytes_to_read); // fill the rest with silence if (bytes_to_rb < bytes_to_read) { // TODO: set some flag for underrun? JAMI_WARN("Dropped %lu bytes", bytes_to_read - bytes_to_rb); } } /* Tell the ringbuffer thread there is work to do. If it is already * running, the lock will not be available. We are unable to wait * here in the process() thread, but we don't need to signal * in that case, because the ringbuffer thread will read all the * data queued before waiting again. */ if (context->ringbuffer_thread_mutex_.try_lock()) { context->data_ready_.notify_one(); context->ringbuffer_thread_mutex_.unlock(); } return 0; } int JackLayer::process_playback(jack_nframes_t frames, void* arg) { JackLayer* context = static_cast<JackLayer*>(arg); for (unsigned i = 0; i < context->out_ringbuffers_.size(); ++i) { // write to output jack_default_audio_sample_t* out_buffers = static_cast<jack_default_audio_sample_t*>( jack_port_get_buffer(context->out_ports_[i], frames)); const size_t bytes_to_write = frames * sizeof(*out_buffers); size_t bytes_from_rb = jack_ringbuffer_read(context->out_ringbuffers_[i], (char*) out_buffers, bytes_to_write); // fill the rest with silence if (bytes_from_rb < bytes_to_write) { const size_t frames_read = bytes_from_rb / sizeof(*out_buffers); memset(out_buffers + frames_read, 0, bytes_to_write - bytes_from_rb); } } return 0; } /** * Start the capture and playback. */ void JackLayer::startStream(AudioDeviceType) { std::lock_guard lock(mutex_); if (status_ != Status::Idle) return; status_ = Status::Started; if (jack_activate(playbackClient_) or jack_activate(captureClient_)) { JAMI_ERR("Unable to activate JACK client"); return; } ringbuffer_thread_ = std::thread(&JackLayer::ringbuffer_worker, this); connectPorts(playbackClient_, JackPortIsInput, out_ports_); connectPorts(captureClient_, JackPortIsOutput, in_ports_); } void JackLayer::onShutdown(void* /* data */) { JAMI_WARN("JACK server shutdown"); // FIXME: handle this safely } /** * Stop playback and capture. */ void JackLayer::stopStream(AudioDeviceType) { std::lock_guard lock(mutex_); if (status_ != Status::Started) return; status_ = Status::Idle; data_ready_.notify_one(); if (jack_deactivate(playbackClient_) or jack_deactivate(captureClient_)) { JAMI_ERR("Unable to deactivate JACK client"); } if (ringbuffer_thread_.joinable()) ringbuffer_thread_.join(); flushMain(); flushUrgent(); } } // namespace jami
12,978
C++
.cpp
359
28.818942
103
0.617743
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,775
opensllayer.cpp
savoirfairelinux_jami-daemon/src/media/audio/opensl/opensllayer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "opensllayer.h" #include "client/ring_signal.h" #include "audio/ringbufferpool.h" #include "audio/ringbuffer.h" #include "libav_utils.h" #include "manager.h" #include "logger.h" #include <SLES/OpenSLES_AndroidConfiguration.h> #include <thread> #include <chrono> #include <cstdio> #include <cassert> #include <unistd.h> namespace jami { // Constructor OpenSLLayer::OpenSLLayer(const AudioPreference& pref) : AudioLayer(pref) {} // Destructor OpenSLLayer::~OpenSLLayer() { shutdownAudioEngine(); } void OpenSLLayer::startStream(AudioDeviceType stream) { using namespace std::placeholders; std::lock_guard lock(mutex_); if (!engineObject_) initAudioEngine(); JAMI_WARN("Start OpenSL audio layer"); if (stream == AudioDeviceType::PLAYBACK) { if (not player_) { try { player_.reset(new opensl::AudioPlayer(hardwareFormat_, hardwareBuffSize_, engineInterface_, SL_ANDROID_STREAM_VOICE)); player_->setBufQueue(&playBufQueue_, &freePlayBufQueue_); player_->registerCallback(std::bind(&OpenSLLayer::engineServicePlay, this)); player_->start(); playbackChanged(true); } catch (const std::exception& e) { JAMI_ERR("Error initializing audio playback: %s", e.what()); } if (recorder_) startAudioCapture(); } } else if (stream == AudioDeviceType::RINGTONE) { if (not ringtone_) { try { ringtone_.reset(new opensl::AudioPlayer(hardwareFormat_, hardwareBuffSize_, engineInterface_, SL_ANDROID_STREAM_VOICE)); ringtone_->setBufQueue(&ringBufQueue_, &freeRingBufQueue_); ringtone_->registerCallback(std::bind(&OpenSLLayer::engineServiceRing, this)); ringtone_->start(); } catch (const std::exception& e) { JAMI_ERR("Error initializing ringtone playback: %s", e.what()); } } } else if (stream == AudioDeviceType::CAPTURE) { if (not recorder_) { std::lock_guard lck(recMtx); try { recorder_.reset( new opensl::AudioRecorder(hardwareFormat_, hardwareBuffSize_, engineInterface_)); recorder_->setBufQueues(&freeRecBufQueue_, &recBufQueue_); recorder_->registerCallback(std::bind(&OpenSLLayer::engineServiceRec, this)); setHasNativeAEC(recorder_->hasNativeAEC()); setHasNativeNS(recorder_->hasNativeNS()); } catch (const std::exception& e) { JAMI_ERR("Error initializing audio capture: %s", e.what()); } if (player_) startAudioCapture(); } } JAMI_WARN("OpenSL audio layer started"); status_ = Status::Started; } void OpenSLLayer::stopStream(AudioDeviceType stream) { std::lock_guard lock(mutex_); if (!engineObject_) return; // bufs_ should be initialized JAMI_WARN("Stopping OpenSL audio layer for type %u", (unsigned) stream); if (stream == AudioDeviceType::PLAYBACK) { if (player_) { playbackChanged(false); player_->stop(); player_.reset(); } freePlayBufQueue_.clear(); for (int i = 0; i < BUF_COUNT; i++) freePlayBufQueue_.push(&bufs_[i]); playBufQueue_.clear(); } else if (stream == AudioDeviceType::RINGTONE) { if (ringtone_) { ringtone_->stop(); ringtone_.reset(); } // Flush buffer freeRingBufQueue_.clear(); for (int i = BUF_COUNT; i < 2 * BUF_COUNT; i++) freeRingBufQueue_.push(&bufs_[i]); ringBufQueue_.clear(); } else if (stream == AudioDeviceType::CAPTURE) { stopAudioCapture(); // Flush buffer freeRecBufQueue_.clear(); for (int i = 2 * BUF_COUNT; i < 3 * BUF_COUNT; i++) freeRecBufQueue_.push(&bufs_[i]); recBufQueue_.clear(); } if (not player_ and not ringtone_ and not recorder_) status_ = Status::Idle; flush(); } std::vector<sample_buf> allocateSampleBufs(unsigned count, size_t sizeInByte) { std::vector<sample_buf> bufs; if (!count || !sizeInByte) return bufs; bufs.reserve(count); size_t allocSize = (sizeInByte + 3) & ~3; // padding to 4 bytes aligned for (unsigned i = 0; i < count; i++) bufs.emplace_back(allocSize, sizeInByte); return bufs; } void OpenSLLayer::initAudioEngine() { JAMI_WARN("OpenSL init started"); std::vector<int32_t> hw_infos; hw_infos.reserve(4); emitSignal<libjami::ConfigurationSignal::GetHardwareAudioFormat>(&hw_infos); hardwareFormat_ = AudioFormat(hw_infos[0], 1, AV_SAMPLE_FMT_FLT); // Mono on Android hardwareBuffSize_ = hw_infos[1]; hardwareFormatAvailable(hardwareFormat_, hardwareBuffSize_); SLASSERT(slCreateEngine(&engineObject_, 0, nullptr, 0, nullptr, nullptr)); SLASSERT((*engineObject_)->Realize(engineObject_, SL_BOOLEAN_FALSE)); SLASSERT((*engineObject_)->GetInterface(engineObject_, SL_IID_ENGINE, &engineInterface_)); size_t bufSize = hardwareBuffSize_ * hardwareFormat_.getBytesPerFrame(); JAMI_LOG("OpenSL init: using buffer of {:d} bytes to support {} with {:d} samples per channel", bufSize, hardwareFormat_.toString(), hardwareBuffSize_); bufs_ = allocateSampleBufs(BUF_COUNT * 3, bufSize); for (int i = 0; i < BUF_COUNT; i++) freePlayBufQueue_.push(&bufs_[i]); for (int i = BUF_COUNT; i < 2 * BUF_COUNT; i++) freeRingBufQueue_.push(&bufs_[i]); for (int i = 2 * BUF_COUNT; i < 3 * BUF_COUNT; i++) freeRecBufQueue_.push(&bufs_[i]); JAMI_WARN("OpenSL init ended"); } void OpenSLLayer::shutdownAudioEngine() { JAMI_DBG("Stopping OpenSL"); stopAudioCapture(); if (player_) { player_->stop(); player_.reset(); } if (ringtone_) { ringtone_->stop(); ringtone_.reset(); } // destroy engine object, and invalidate all associated interfaces JAMI_DBG("Shutdown audio engine"); if (engineObject_ != nullptr) { (*engineObject_)->Destroy(engineObject_); engineObject_ = nullptr; engineInterface_ = nullptr; } freeRecBufQueue_.clear(); recBufQueue_.clear(); freePlayBufQueue_.clear(); playBufQueue_.clear(); freeRingBufQueue_.clear(); ringBufQueue_.clear(); startedCv_.notify_all(); bufs_.clear(); } uint32_t OpenSLLayer::dbgEngineGetBufCount() { uint32_t count_player = player_->dbgGetDevBufCount(); count_player += freePlayBufQueue_.size(); count_player += playBufQueue_.size(); uint32_t count_ringtone = ringtone_->dbgGetDevBufCount(); count_ringtone += freeRingBufQueue_.size(); count_ringtone += ringBufQueue_.size(); JAMI_ERR("Buf Disrtibutions: PlayerDev=%zu, PlayQ=%u, FreePlayQ=%u", player_->dbgGetDevBufCount(), playBufQueue_.size(), freePlayBufQueue_.size()); JAMI_ERR("Buf Disrtibutions: RingDev=%zu, RingQ=%u, FreeRingQ=%u", ringtone_->dbgGetDevBufCount(), ringBufQueue_.size(), freeRingBufQueue_.size()); if (count_player != BUF_COUNT) { JAMI_ERR("====Lost Bufs among the queue(supposed = %d, found = %u)", BUF_COUNT, count_player); } return count_player; } void OpenSLLayer::engineServicePlay() { sample_buf* buf; while (player_ and freePlayBufQueue_.front(&buf)) { if (auto dat = getToPlay(hardwareFormat_, hardwareBuffSize_)) { buf->size_ = dat->pointer()->nb_samples * dat->getFormat().getBytesPerFrame(); if (buf->size_ > buf->cap_) { JAMI_ERR("buf->size_(%zu) > buf->cap_(%zu)", buf->size_, buf->cap_); break; } if (not dat->pointer()->data[0] or not buf->buf_) { JAMI_ERR("null bufer %p -> %p %d", dat->pointer()->data[0], buf->buf_, dat->pointer()->nb_samples); break; } memcpy(buf->buf_, dat->pointer()->data[0], buf->size_); if (!playBufQueue_.push(buf)) { JAMI_WARN("playThread player_ PLAY_KICKSTART_BUFFER_COUNT 1"); break; } else freePlayBufQueue_.pop(); } else { break; } } } void OpenSLLayer::engineServiceRing() { sample_buf* buf; while (ringtone_ and freeRingBufQueue_.front(&buf)) { if (auto dat = getToRing(hardwareFormat_, hardwareBuffSize_)) { buf->size_ = dat->pointer()->nb_samples * dat->getFormat().getBytesPerFrame(); if (buf->size_ > buf->cap_) { JAMI_ERR("buf->size_(%zu) > buf->cap_(%zu)", buf->size_, buf->cap_); break; } if (not dat->pointer()->data[0] or not buf->buf_) { JAMI_ERR("null bufer %p -> %p %d", dat->pointer()->data[0], buf->buf_, dat->pointer()->nb_samples); break; } memcpy(buf->buf_, dat->pointer()->data[0], buf->size_); if (!ringBufQueue_.push(buf)) { JAMI_WARN("playThread ringtone_ PLAY_KICKSTART_BUFFER_COUNT 1"); break; } else freeRingBufQueue_.pop(); } else { break; } } } void OpenSLLayer::engineServiceRec() { recCv.notify_one(); } void OpenSLLayer::startAudioCapture() { if (not recorder_) return; JAMI_DBG("Start audio capture"); if (recThread.joinable()) return; recThread = std::thread([&]() { std::unique_lock lck(recMtx); if (recorder_) recorder_->start(); recordChanged(true); while (recorder_) { recCv.wait_for(lck, std::chrono::seconds(1)); if (not recorder_) break; sample_buf* buf; while (recBufQueue_.front(&buf)) { recBufQueue_.pop(); if (buf->size_ > 0) { auto nb_samples = buf->size_ / hardwareFormat_.getBytesPerFrame(); auto out = std::make_shared<AudioFrame>(hardwareFormat_, nb_samples); if (isCaptureMuted_) libav_utils::fillWithSilence(out->pointer()); else memcpy(out->pointer()->data[0], buf->buf_, buf->size_); putRecorded(std::move(out)); } buf->size_ = 0; freeRecBufQueue_.push(buf); } } recordChanged(false); }); JAMI_DBG("Audio capture started"); } void OpenSLLayer::stopAudioCapture() { JAMI_DBG("Stop audio capture"); { std::lock_guard lck(recMtx); if (recorder_) { recorder_->stop(); recorder_.reset(); } } if (recThread.joinable()) { recCv.notify_all(); recThread.join(); } JAMI_DBG("Audio capture stopped"); } std::vector<std::string> OpenSLLayer::getCaptureDeviceList() const { std::vector<std::string> captureDeviceList; // Although OpenSL ES specification allows enumerating // available output (and also input) devices, NDK implementation is not mature enough to // obtain or select proper one (SLAudioIODeviceCapabilitiesItf, the official interface // to obtain such an information)-> SL_FEATURE_UNSUPPORTED SLuint32 InputDeviceIDs[MAX_NUMBER_INPUT_DEVICES]; SLint32 numInputs = 0; SLboolean mic_available = SL_BOOLEAN_FALSE; SLuint32 mic_deviceID = 0; SLresult res; // Get the Audio IO DEVICE CAPABILITIES interface, implicit SLAudioIODeviceCapabilitiesItf deviceCapabilities {nullptr}; res = (*engineObject_) ->GetInterface(engineObject_, SL_IID_AUDIOIODEVICECAPABILITIES, (void*) &deviceCapabilities); if (res != SL_RESULT_SUCCESS) return captureDeviceList; numInputs = MAX_NUMBER_INPUT_DEVICES; res = (*deviceCapabilities) ->GetAvailableAudioInputs(deviceCapabilities, &numInputs, InputDeviceIDs); if (res != SL_RESULT_SUCCESS) return captureDeviceList; // Search for either earpiece microphone or headset microphone input // device - with a preference for the latter for (int i = 0; i < numInputs; i++) { SLAudioInputDescriptor audioInputDescriptor_; res = (*deviceCapabilities) ->QueryAudioInputCapabilities(deviceCapabilities, InputDeviceIDs[i], &audioInputDescriptor_); if (res != SL_RESULT_SUCCESS) return captureDeviceList; if (audioInputDescriptor_.deviceConnection == SL_DEVCONNECTION_ATTACHED_WIRED and audioInputDescriptor_.deviceScope == SL_DEVSCOPE_USER and audioInputDescriptor_.deviceLocation == SL_DEVLOCATION_HEADSET) { JAMI_DBG("SL_DEVCONNECTION_ATTACHED_WIRED : mic_deviceID: %d", InputDeviceIDs[i]); mic_deviceID = InputDeviceIDs[i]; mic_available = SL_BOOLEAN_TRUE; break; } else if (audioInputDescriptor_.deviceConnection == SL_DEVCONNECTION_INTEGRATED and audioInputDescriptor_.deviceScope == SL_DEVSCOPE_USER and audioInputDescriptor_.deviceLocation == SL_DEVLOCATION_HANDSET) { JAMI_DBG("SL_DEVCONNECTION_INTEGRATED : mic_deviceID: %d", InputDeviceIDs[i]); mic_deviceID = InputDeviceIDs[i]; mic_available = SL_BOOLEAN_TRUE; break; } } if (!mic_available) JAMI_ERR("No mic available"); return captureDeviceList; } std::vector<std::string> OpenSLLayer::getPlaybackDeviceList() const { std::vector<std::string> playbackDeviceList; return playbackDeviceList; } void OpenSLLayer::updatePreference(AudioPreference& /*preference*/, int /*index*/, AudioDeviceType /*type*/) {} void dumpAvailableEngineInterfaces() { SLresult result; JAMI_DBG("Engine Interfaces"); SLuint32 numSupportedInterfaces; result = slQueryNumSupportedEngineInterfaces(&numSupportedInterfaces); assert(SL_RESULT_SUCCESS == result); result = slQueryNumSupportedEngineInterfaces(NULL); assert(SL_RESULT_PARAMETER_INVALID == result); JAMI_DBG("Engine number of supported interfaces %u", numSupportedInterfaces); for (SLuint32 i = 0; i < numSupportedInterfaces; i++) { SLInterfaceID pInterfaceId; slQuerySupportedEngineInterfaces(i, &pInterfaceId); const char* nm = "unknown iid"; if (pInterfaceId == SL_IID_NULL) nm = "null"; else if (pInterfaceId == SL_IID_OBJECT) nm = "object"; else if (pInterfaceId == SL_IID_AUDIOIODEVICECAPABILITIES) nm = "audiodevicecapabilities"; else if (pInterfaceId == SL_IID_LED) nm = "led"; else if (pInterfaceId == SL_IID_VIBRA) nm = "vibra"; else if (pInterfaceId == SL_IID_METADATAEXTRACTION) nm = "metadataextraction"; else if (pInterfaceId == SL_IID_METADATATRAVERSAL) nm = "metadatatraversal"; else if (pInterfaceId == SL_IID_DYNAMICSOURCE) nm = "dynamicsource"; else if (pInterfaceId == SL_IID_OUTPUTMIX) nm = "outputmix"; else if (pInterfaceId == SL_IID_PLAY) nm = "play"; else if (pInterfaceId == SL_IID_PREFETCHSTATUS) nm = "prefetchstatus"; else if (pInterfaceId == SL_IID_PLAYBACKRATE) nm = "playbackrate"; else if (pInterfaceId == SL_IID_SEEK) nm = "seek"; else if (pInterfaceId == SL_IID_RECORD) nm = "record"; else if (pInterfaceId == SL_IID_EQUALIZER) nm = "equalizer"; else if (pInterfaceId == SL_IID_VOLUME) nm = "volume"; else if (pInterfaceId == SL_IID_DEVICEVOLUME) nm = "devicevolume"; else if (pInterfaceId == SL_IID_BUFFERQUEUE) nm = "bufferqueue"; else if (pInterfaceId == SL_IID_PRESETREVERB) nm = "presetreverb"; else if (pInterfaceId == SL_IID_ENVIRONMENTALREVERB) nm = "environmentalreverb"; else if (pInterfaceId == SL_IID_EFFECTSEND) nm = "effectsend"; else if (pInterfaceId == SL_IID_3DGROUPING) nm = "3dgrouping"; else if (pInterfaceId == SL_IID_3DCOMMIT) nm = "3dcommit"; else if (pInterfaceId == SL_IID_3DLOCATION) nm = "3dlocation"; else if (pInterfaceId == SL_IID_3DDOPPLER) nm = "3ddoppler"; else if (pInterfaceId == SL_IID_3DSOURCE) nm = "3dsource"; else if (pInterfaceId == SL_IID_3DMACROSCOPIC) nm = "3dmacroscopic"; else if (pInterfaceId == SL_IID_MUTESOLO) nm = "mutesolo"; else if (pInterfaceId == SL_IID_DYNAMICINTERFACEMANAGEMENT) nm = "dynamicinterfacemanagement"; else if (pInterfaceId == SL_IID_MIDIMESSAGE) nm = "midimessage"; else if (pInterfaceId == SL_IID_MIDIMUTESOLO) nm = "midimutesolo"; else if (pInterfaceId == SL_IID_MIDITEMPO) nm = "miditempo"; else if (pInterfaceId == SL_IID_MIDITIME) nm = "miditime"; else if (pInterfaceId == SL_IID_AUDIODECODERCAPABILITIES) nm = "audiodecodercapabilities"; else if (pInterfaceId == SL_IID_AUDIOENCODERCAPABILITIES) nm = "audioencodercapabilities"; else if (pInterfaceId == SL_IID_AUDIOENCODER) nm = "audioencoder"; else if (pInterfaceId == SL_IID_BASSBOOST) nm = "bassboost"; else if (pInterfaceId == SL_IID_PITCH) nm = "pitch"; else if (pInterfaceId == SL_IID_RATEPITCH) nm = "ratepitch"; else if (pInterfaceId == SL_IID_VIRTUALIZER) nm = "virtualizer"; else if (pInterfaceId == SL_IID_VISUALIZATION) nm = "visualization"; else if (pInterfaceId == SL_IID_ENGINE) nm = "engine"; else if (pInterfaceId == SL_IID_ENGINECAPABILITIES) nm = "enginecapabilities"; else if (pInterfaceId == SL_IID_THREADSYNC) nm = "theadsync"; else if (pInterfaceId == SL_IID_ANDROIDEFFECT) nm = "androideffect"; else if (pInterfaceId == SL_IID_ANDROIDEFFECTSEND) nm = "androideffectsend"; else if (pInterfaceId == SL_IID_ANDROIDEFFECTCAPABILITIES) nm = "androideffectcapabilities"; else if (pInterfaceId == SL_IID_ANDROIDCONFIGURATION) nm = "androidconfiguration"; else if (pInterfaceId == SL_IID_ANDROIDSIMPLEBUFFERQUEUE) nm = "simplebuferqueue"; // else if (pInterfaceId==//SL_IID_ANDROIDBUFFERQUEUESOURCE) nm="bufferqueuesource"; JAMI_DBG("%s,", nm); } } } // namespace jami
20,558
C++
.cpp
531
29.184557
101
0.587443
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,776
audio_recorder.cpp
savoirfairelinux_jami-daemon/src/media/audio/opensl/audio_recorder.cpp
/* * Copyright 2015 The Android Open Source Project * Copyright 2015-2024 Savoir-faire Linux Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstring> #include <cstdlib> #include "audio_recorder.h" namespace jami { namespace opensl { /* * bqRecorderCallback(): called for every buffer is full; * pass directly to handler */ void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void* rec) { (static_cast<AudioRecorder*>(rec))->processSLCallback(bq); } void AudioRecorder::processSLCallback(SLAndroidSimpleBufferQueueItf bq) { try { sample_buf* dataBuf {nullptr}; if (devShadowQueue_.front(&dataBuf)) { devShadowQueue_.pop(); dataBuf->size_ = dataBuf->cap_; // device only calls us when it is really full if (dataBuf != &silentBuf_) recQueue_->push(dataBuf); } sample_buf* freeBuf; while (freeQueue_->front(&freeBuf) && devShadowQueue_.push(freeBuf)) { freeQueue_->pop(); SLASSERT((*bq)->Enqueue(bq, freeBuf->buf_, freeBuf->cap_)); } // should leave the device to sleep to save power if no buffers if (devShadowQueue_.size() == 0) { // JAMI_WARN("OpenSL: processSLCallback empty queue"); (*bq)->Enqueue(bq, silentBuf_.buf_, silentBuf_.cap_); devShadowQueue_.push(&silentBuf_); } if (callback_) callback_(); } catch (const std::exception& e) { JAMI_ERR("OpenSL: processSLCallback exception: %s", e.what()); } } AudioRecorder::AudioRecorder(jami::AudioFormat sampleFormat, size_t bufSize, SLEngineItf slEngine) : sampleInfo_(sampleFormat) { JAMI_DBG("Creating OpenSL record stream"); // configure audio source/ SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, nullptr}; SLDataSource audioSrc = {&loc_dev, nullptr}; // configure audio sink SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, DEVICE_SHADOW_BUFFER_QUEUE_LEN}; auto format_pcm = convertToSLSampleFormat(sampleInfo_); SLDataSink audioSnk = {&loc_bq, &format_pcm}; // create audio recorder // (requires the RECORD_AUDIO permission) const SLInterfaceID ids[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION, SL_IID_ANDROIDACOUSTICECHOCANCELLATION, SL_IID_ANDROIDAUTOMATICGAINCONTROL, SL_IID_ANDROIDNOISESUPPRESSION}; const SLboolean req[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE, SL_BOOLEAN_FALSE, SL_BOOLEAN_FALSE}; SLresult result; result = (*slEngine)->CreateAudioRecorder(slEngine, &recObjectItf_, &audioSrc, &audioSnk, sizeof(ids) / sizeof(ids[0]), ids, req); SLASSERT(result); SLAndroidConfigurationItf recordConfig; SLint32 streamType = SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION; result = (*recObjectItf_) ->GetInterface(recObjectItf_, SL_IID_ANDROIDCONFIGURATION, &recordConfig); SLASSERT(result); result = (*recordConfig) ->SetConfiguration(recordConfig, SL_ANDROID_KEY_RECORDING_PRESET, &streamType, sizeof(SLint32)); bool aec {true}, agc(true), ns(true); result = (*recObjectItf_)->Realize(recObjectItf_, SL_BOOLEAN_FALSE); SLASSERT(result); result = (*recObjectItf_)->GetInterface(recObjectItf_, SL_IID_RECORD, &recItf_); SLASSERT(result); /* Check actual performance mode granted*/ SLuint32 modeRetrieved = SL_ANDROID_PERFORMANCE_NONE; SLuint32 modeSize = sizeof(SLuint32); result = (*recordConfig) ->GetConfiguration(recordConfig, SL_ANDROID_KEY_PERFORMANCE_MODE, &modeSize, (void*) &modeRetrieved); if (result == SL_RESULT_SUCCESS) { JAMI_WARN("Actual performance mode is %u\n", modeRetrieved); } /* Enable AEC if requested */ if (aec) { SLAndroidAcousticEchoCancellationItf aecItf; result = (*recObjectItf_) ->GetInterface(recObjectItf_, SL_IID_ANDROIDACOUSTICECHOCANCELLATION, (void*) &aecItf); JAMI_WARN("AEC is %savailable\n", SL_RESULT_SUCCESS == result ? "" : "not "); if (SL_RESULT_SUCCESS == result) { SLboolean enabled; if ((*aecItf)->IsEnabled(aecItf, &enabled) == SL_RESULT_SUCCESS) { JAMI_WARN("AEC was %s\n", enabled ? "enabled" : "not enabled"); (*aecItf)->SetEnabled(aecItf, true); if ((*aecItf)->IsEnabled(aecItf, &enabled) == SL_RESULT_SUCCESS) { JAMI_WARN("AEC is now %s\n", enabled ? "enabled" : "not enabled"); hasNativeAEC_ = enabled; } } } } /* Enable AGC if requested */ if (agc) { SLAndroidAutomaticGainControlItf agcItf; result = (*recObjectItf_) ->GetInterface(recObjectItf_, SL_IID_ANDROIDAUTOMATICGAINCONTROL, (void*) &agcItf); JAMI_WARN("AGC is %savailable\n", SL_RESULT_SUCCESS == result ? "" : "not "); if (SL_RESULT_SUCCESS == result) { SLboolean enabled; if ((*agcItf)->IsEnabled(agcItf, &enabled) == SL_RESULT_SUCCESS) { JAMI_WARN("AGC was %s\n", enabled ? "enabled" : "not enabled"); (*agcItf)->SetEnabled(agcItf, true); if ((*agcItf)->IsEnabled(agcItf, &enabled) == SL_RESULT_SUCCESS) { JAMI_WARN("AGC is now %s\n", enabled ? "enabled" : "not enabled"); } } } } /* Enable NS if requested */ if (ns) { SLAndroidNoiseSuppressionItf nsItf; result = (*recObjectItf_) ->GetInterface(recObjectItf_, SL_IID_ANDROIDNOISESUPPRESSION, (void*) &nsItf); JAMI_WARN("NS is %savailable\n", SL_RESULT_SUCCESS == result ? "" : "not "); if (SL_RESULT_SUCCESS == result) { SLboolean enabled; if ((*nsItf)->IsEnabled(nsItf, &enabled) == SL_RESULT_SUCCESS) { JAMI_WARN("NS was %s\n", enabled ? "enabled" : "not enabled"); (*nsItf)->SetEnabled(nsItf, true); if ((*nsItf)->IsEnabled(nsItf, &enabled) == SL_RESULT_SUCCESS) { JAMI_WARN("NS is now %s\n", enabled ? "enabled" : "not enabled"); hasNativeNS_ = enabled; } } } } result = (*recObjectItf_) ->GetInterface(recObjectItf_, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recBufQueueItf_); SLASSERT(result); result = (*recBufQueueItf_)->RegisterCallback(recBufQueueItf_, bqRecorderCallback, this); SLASSERT(result); silentBuf_ = {(format_pcm.containerSize >> 3) * format_pcm.numChannels * bufSize}; silentBuf_.size_ = silentBuf_.cap_; av_samples_set_silence(&silentBuf_.buf_, 0, (int)bufSize, (int)sampleInfo_.nb_channels, sampleInfo_.sampleFormat); } bool AudioRecorder::start() { JAMI_DBG("OpenSL record start"); if (!freeQueue_ || !recQueue_) { JAMI_ERR("====NULL pointer to Start(%p, %p)", freeQueue_, recQueue_); return false; } audioBufCount = 0; SLresult result; // in case already recording, stop recording and clear buffer queue result = (*recItf_)->SetRecordState(recItf_, SL_RECORDSTATE_STOPPED); SLASSERT(result); result = (*recBufQueueItf_)->Clear(recBufQueueItf_); SLASSERT(result); for (int i = 0; i < RECORD_DEVICE_KICKSTART_BUF_COUNT; i++) { sample_buf* buf = NULL; if (!freeQueue_->front(&buf)) { JAMI_ERR("=====OutOfFreeBuffers @ startingRecording @ (%d)", i); break; } freeQueue_->pop(); assert(buf->buf_ && buf->cap_ && !buf->size_); result = (*recBufQueueItf_)->Enqueue(recBufQueueItf_, buf->buf_, buf->cap_); SLASSERT(result); devShadowQueue_.push(buf); } result = (*recItf_)->SetRecordState(recItf_, SL_RECORDSTATE_RECORDING); SLASSERT(result); return result == SL_RESULT_SUCCESS; } bool AudioRecorder::stop() { JAMI_DBG("OpenSL record stop"); // in case already recording, stop recording and clear buffer queue SLuint32 curState; SLresult result = (*recItf_)->GetRecordState(recItf_, &curState); SLASSERT(result); if (curState == SL_RECORDSTATE_STOPPED) return true; result = (*recItf_)->SetRecordState(recItf_, SL_RECORDSTATE_STOPPED); SLASSERT(result); callback_ = {}; result = (*recBufQueueItf_)->Clear(recBufQueueItf_); SLASSERT(result); sample_buf* buf {nullptr}; while (devShadowQueue_.front(&buf)) { devShadowQueue_.pop(); freeQueue_->push(buf); } return true; } AudioRecorder::~AudioRecorder() { JAMI_DBG("Destroying OpenSL record stream"); // destroy audio recorder object, and invalidate all associated interfaces if (recObjectItf_) { (*recObjectItf_)->Destroy(recObjectItf_); } } void AudioRecorder::setBufQueues(AudioQueue* freeQ, AudioQueue* recQ) { assert(freeQ && recQ); freeQueue_ = freeQ; recQueue_ = recQ; } size_t AudioRecorder::dbgGetDevBufCount() { return devShadowQueue_.size(); } } // namespace opensl } // namespace jami
10,853
C++
.cpp
261
31.095785
118
0.579291
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,777
audio_player.cpp
savoirfairelinux_jami-daemon/src/media/audio/opensl/audio_player.cpp
/* * Copyright 2015 The Android Open Source Project * Copyright 2015-2024 Savoir-faire Linux Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "audio_player.h" #include "logger.h" #include <SLES/OpenSLES_AndroidConfiguration.h> #include <cstdlib> namespace jami { namespace opensl { /* * Called by OpenSL SimpleBufferQueue for every audio buffer played * directly pass through to our handler. * The regularity of this callback from openSL/Android System affects * playback continuity. If it does not callback in the regular time * slot, you are under big pressure for audio processing[here we do * not do any filtering/mixing]. Callback from fast audio path are * much more regular than other audio paths by my observation. If it * very regular, you could buffer much less audio samples between * recorder and player, hence lower latency. */ void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* ctx) { (static_cast<AudioPlayer*>(ctx))->processSLCallback(bq); } void AudioPlayer::processSLCallback(SLAndroidSimpleBufferQueueItf bq) { std::unique_lock lk(m_, std::defer_lock); if (!lk.try_lock()) return; // retrieve the finished device buf and put onto the free queue // so recorder could re-use it sample_buf* buf; if (!devShadowQueue_.front(&buf)) { JAMI_ERR("AudioPlayer buffer lost"); /* * This should not happen: we got a callback, * but we have no buffer in deviceShadowedQueue * we lost buffers this way...(ERROR) */ return; } devShadowQueue_.pop(); if (buf != &silentBuf_) { buf->size_ = 0; if (!freeQueue_->push(buf)) { JAMI_ERR("buffer lost"); } } if (callback_) callback_(); while (playQueue_->front(&buf) && devShadowQueue_.push(buf)) { if ((*bq)->Enqueue(bq, buf->buf_, buf->size_) != SL_RESULT_SUCCESS) { devShadowQueue_.pop(); JAMI_ERR("enqueue failed %zu %d %d %d", buf->size_, freeQueue_->size(), playQueue_->size(), devShadowQueue_.size()); break; } else playQueue_->pop(); } if (devShadowQueue_.size() == 0) { for (int i = 0; i < DEVICE_SHADOW_BUFFER_QUEUE_LEN; i++) { if ((*bq)->Enqueue(bq, silentBuf_.buf_, silentBuf_.size_) == SL_RESULT_SUCCESS) { devShadowQueue_.push(&silentBuf_); } else { JAMI_ERR("Enqueue silentBuf_ failed"); } } } } AudioPlayer::AudioPlayer(jami::AudioFormat sampleFormat, size_t bufSize, SLEngineItf slEngine, SLint32 streamType) : sampleInfo_(sampleFormat) { JAMI_DBG("Creating OpenSL playback stream %s", sampleFormat.toString().c_str()); SLresult result; result = (*slEngine)->CreateOutputMix(slEngine, &outputMixObjectItf_, 0, nullptr, nullptr); SLASSERT(result); // realize the output mix result = (*outputMixObjectItf_)->Realize(outputMixObjectItf_, SL_BOOLEAN_FALSE); SLASSERT(result); // configure audio source SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, DEVICE_SHADOW_BUFFER_QUEUE_LEN}; auto format_pcm = convertToSLSampleFormat(sampleInfo_); SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObjectItf_}; SLDataSink audioSnk = {&loc_outmix, nullptr}; /* * create fast path audio player: SL_IID_BUFFERQUEUE and SL_IID_VOLUME interfaces ok, * NO others! */ SLInterfaceID ids[3] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME, SL_IID_ANDROIDCONFIGURATION}; SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; result = (*slEngine)->CreateAudioPlayer(slEngine, &playerObjectItf_, &audioSrc, &audioSnk, sizeof(ids) / sizeof(ids[0]), ids, req); SLASSERT(result); SLAndroidConfigurationItf playerConfig; result = (*playerObjectItf_) ->GetInterface(playerObjectItf_, SL_IID_ANDROIDCONFIGURATION, &playerConfig); result = (*playerConfig) ->SetConfiguration(playerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32)); // realize the player result = (*playerObjectItf_)->Realize(playerObjectItf_, SL_BOOLEAN_FALSE); SLASSERT(result); // get the play interface result = (*playerObjectItf_)->GetInterface(playerObjectItf_, SL_IID_PLAY, &playItf_); SLASSERT(result); // get the buffer queue interface result = (*playerObjectItf_) ->GetInterface(playerObjectItf_, SL_IID_BUFFERQUEUE, &playBufferQueueItf_); SLASSERT(result); // register callback on the buffer queue result = (*playBufferQueueItf_)->RegisterCallback(playBufferQueueItf_, bqPlayerCallback, this); SLASSERT(result); result = (*playItf_)->SetPlayState(playItf_, SL_PLAYSTATE_STOPPED); SLASSERT(result); silentBuf_ = {(format_pcm.containerSize >> 3) * format_pcm.numChannels * bufSize}; silentBuf_.size_ = silentBuf_.cap_; av_samples_set_silence(&silentBuf_.buf_, 0, (int)bufSize, (int)sampleInfo_.nb_channels, sampleInfo_.sampleFormat); } AudioPlayer::~AudioPlayer() { JAMI_DBG("Destroying OpenSL playback stream"); std::lock_guard lk(m_); // destroy buffer queue audio player object, and invalidate all associated interfaces if (playerObjectItf_) { (*playerObjectItf_)->Destroy(playerObjectItf_); } // destroy output mix object, and invalidate all associated interfaces if (outputMixObjectItf_) { (*outputMixObjectItf_)->Destroy(outputMixObjectItf_); } } void AudioPlayer::setBufQueue(AudioQueue* playQ, AudioQueue* freeQ) { playQueue_ = playQ; freeQueue_ = freeQ; } bool AudioPlayer::start() { JAMI_DBG("OpenSL playback start"); std::unique_lock lk(m_); SLuint32 state; SLresult result = (*playItf_)->GetPlayState(playItf_, &state); if (result != SL_RESULT_SUCCESS) return false; if (state == SL_PLAYSTATE_PLAYING) return true; result = (*playItf_)->SetPlayState(playItf_, SL_PLAYSTATE_STOPPED); SLASSERT(result); devShadowQueue_.push(&silentBuf_); result = (*playBufferQueueItf_)->Enqueue(playBufferQueueItf_, silentBuf_.buf_, silentBuf_.size_); if (result != SL_RESULT_SUCCESS) { JAMI_ERR("Enqueue silentBuf_ failed, result = %d", result); devShadowQueue_.pop(); } lk.unlock(); result = (*playItf_)->SetPlayState(playItf_, SL_PLAYSTATE_PLAYING); SLASSERT(result); return true; } bool AudioPlayer::started() const { if (!playItf_) return false; SLuint32 state; SLresult result = (*playItf_)->GetPlayState(playItf_, &state); return result == SL_RESULT_SUCCESS && state == SL_PLAYSTATE_PLAYING; } void AudioPlayer::stop() { JAMI_DBG("OpenSL playback stop"); SLuint32 state; std::lock_guard lk(m_); SLresult result = (*playItf_)->GetPlayState(playItf_, &state); SLASSERT(result); if (state == SL_PLAYSTATE_STOPPED) return; callback_ = {}; result = (*playItf_)->SetPlayState(playItf_, SL_PLAYSTATE_STOPPED); SLASSERT(result); // Consume all non-completed audio buffers sample_buf* buf = nullptr; while (devShadowQueue_.front(&buf)) { buf->size_ = 0; devShadowQueue_.pop(); freeQueue_->push(buf); } while (playQueue_->front(&buf)) { buf->size_ = 0; playQueue_->pop(); freeQueue_->push(buf); } } void AudioPlayer::playAudioBuffers(unsigned count) { while (count--) { sample_buf* buf = nullptr; if (!playQueue_->front(&buf)) { JAMI_ERR("====Run out of buffers in %s @(count = %d)", __FUNCTION__, count); break; } if (!devShadowQueue_.push(buf)) { break; // PlayerBufferQueue is full!!! } SLresult result = (*playBufferQueueItf_)->Enqueue(playBufferQueueItf_, buf->buf_, buf->size_); if (result != SL_RESULT_SUCCESS) { JAMI_ERR("%s Error @( %p, %zu ), result = %d", __FUNCTION__, (void*) buf->buf_, buf->size_, result); /* * when this happens, a buffer is lost. Need to remove the buffer * from top of the devShadowQueue. Since I do not have it now, * just pop out the one that is being played right now. Afer a * cycle it will be normal. */ devShadowQueue_.front(&buf), devShadowQueue_.pop(); freeQueue_->push(buf); break; } playQueue_->pop(); // really pop out the buffer } } size_t AudioPlayer::dbgGetDevBufCount(void) { return devShadowQueue_.size(); } } // namespace opensl } // namespace jami
10,011
C++
.cpp
266
29.778195
118
0.619602
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,778
audiostream.cpp
savoirfairelinux_jami-daemon/src/media/audio/pulseaudio/audiostream.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audiostream.h" #include "pulselayer.h" #include "logger.h" #include "compiler_intrinsics.h" #include <string_view> #include <stdexcept> using namespace std::literals; namespace jami { AudioStream::AudioStream(pa_context* c, pa_threaded_mainloop* m, const char* desc, AudioDeviceType type, unsigned samplrate, pa_sample_format_t format, const PaDeviceInfos& infos, bool ec, OnReady onReady, OnData onData) : onReady_(std::move(onReady)) , onData_(std::move(onData)) , audiostream_(nullptr) , mainloop_(m) , audioType_(type) { pa_sample_spec sample_spec = {format, samplrate, infos.channel_map.channels}; JAMI_DEBUG("{}: Creating stream with device {} ({}, {}Hz, {} channels)", desc, infos.name, pa_sample_format_to_string(sample_spec.format), samplrate, infos.channel_map.channels); assert(pa_sample_spec_valid(&sample_spec)); assert(pa_channel_map_valid(&infos.channel_map)); std::unique_ptr<pa_proplist, decltype(pa_proplist_free)&> pl(pa_proplist_new(), pa_proplist_free); pa_proplist_sets(pl.get(), PA_PROP_FILTER_WANT, "echo-cancel"); pa_proplist_sets( pl.get(), "filter.apply.echo-cancel.parameters", // needs pulseaudio >= 11.0 "use_volume_sharing=0" // share volume with master sink/source " use_master_format=1" // use format/rate/channels from master sink/source " aec_args=\"" "digital_gain_control=1" " analog_gain_control=0" " experimental_agc=1" "\""); audiostream_ = pa_stream_new_with_proplist(c, desc, &sample_spec, &infos.channel_map, ec ? pl.get() : nullptr); if (!audiostream_) { JAMI_ERR("%s: pa_stream_new() failed : %s", desc, pa_strerror(pa_context_errno(c))); throw std::runtime_error("Unable to create stream\n"); } pa_buffer_attr attributes; attributes.maxlength = pa_usec_to_bytes(160 * PA_USEC_PER_MSEC, &sample_spec); attributes.tlength = pa_usec_to_bytes(80 * PA_USEC_PER_MSEC, &sample_spec); attributes.prebuf = 0; attributes.fragsize = pa_usec_to_bytes(80 * PA_USEC_PER_MSEC, &sample_spec); attributes.minreq = (uint32_t) -1; pa_stream_set_state_callback( audiostream_, [](pa_stream* s, void* user_data) { static_cast<AudioStream*>(user_data)->stateChanged(s); }, this); pa_stream_set_moved_callback( audiostream_, [](pa_stream* s, void* user_data) { static_cast<AudioStream*>(user_data)->moved(s); }, this); constexpr pa_stream_flags_t flags = static_cast<pa_stream_flags_t>( PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_START_CORKED); if (type == AudioDeviceType::PLAYBACK || type == AudioDeviceType::RINGTONE) { pa_stream_set_write_callback( audiostream_, [](pa_stream* /*s*/, size_t bytes, void* userdata) { static_cast<AudioStream*>(userdata)->onData_(bytes); }, this); pa_stream_connect_playback(audiostream_, infos.name.empty() ? nullptr : infos.name.c_str(), &attributes, flags, nullptr, nullptr); } else if (type == AudioDeviceType::CAPTURE) { pa_stream_set_read_callback( audiostream_, [](pa_stream* /*s*/, size_t bytes, void* userdata) { static_cast<AudioStream*>(userdata)->onData_(bytes); }, this); pa_stream_connect_record(audiostream_, infos.name.empty() ? nullptr : infos.name.c_str(), &attributes, flags); } } void disconnectStream(pa_stream* s) { // make sure we don't get any further callback pa_stream_set_write_callback(s, nullptr, nullptr); pa_stream_set_read_callback(s, nullptr, nullptr); pa_stream_set_moved_callback(s, nullptr, nullptr); pa_stream_set_underflow_callback(s, nullptr, nullptr); pa_stream_set_overflow_callback(s, nullptr, nullptr); pa_stream_set_suspended_callback(s, nullptr, nullptr); pa_stream_set_started_callback(s, nullptr, nullptr); } void destroyStream(pa_stream* s) { pa_stream_disconnect(s); pa_stream_set_state_callback(s, nullptr, nullptr); disconnectStream(s); pa_stream_unref(s); } AudioStream::~AudioStream() { stop(); } void AudioStream::start() { pa_stream_cork(audiostream_, 0, nullptr, nullptr); // trigger echo cancel check moved(audiostream_); } void AudioStream::stop() { if (not audiostream_) return; JAMI_DBG("Destroying stream with device %s", pa_stream_get_device_name(audiostream_)); if (pa_stream_get_state(audiostream_) == PA_STREAM_CREATING) { disconnectStream(audiostream_); pa_stream_set_state_callback( audiostream_, [](pa_stream* s, void*) { destroyStream(s); }, nullptr); } else { destroyStream(audiostream_); } audiostream_ = nullptr; std::unique_lock lock(mutex_); for (auto op : ongoing_ops) pa_operation_cancel(op); // wait for all operations to end cond_.wait(lock, [this]{ return ongoing_ops.empty(); }); } void AudioStream::moved(pa_stream* s) { audiostream_ = s; JAMI_LOG("[audiostream] Stream moved: {:d}, {:s}", pa_stream_get_index(s), pa_stream_get_device_name(s)); if (audioType_ == AudioDeviceType::CAPTURE) { // check for echo cancel const char* name = pa_stream_get_device_name(s); if (!name) { JAMI_ERR("[audiostream] moved() unable to get audio stream device"); return; } auto* op = pa_context_get_source_info_by_name( pa_stream_get_context(s), name, [](pa_context* /*c*/, const pa_source_info* i, int /*eol*/, void* userdata) { AudioStream* thisPtr = (AudioStream*) userdata; // this closure gets called twice by pulse for some reason // the 2nd time, i is invalid if (!i) { // JAMI_ERROR("[audiostream] source info not found"); return; } if (!thisPtr) { JAMI_ERROR("[audiostream] AudioStream pointer became invalid during pa_source_info_cb_t callback!"); return; } // string compare bool usingEchoCancel = std::string_view(i->driver) == "module-echo-cancel.c"sv; JAMI_WARNING("[audiostream] capture stream using pulse echo cancel module? {} ({})", usingEchoCancel ? "yes" : "no", i->name); thisPtr->echoCancelCb(usingEchoCancel); }, this); std::lock_guard lock(mutex_); pa_operation_set_state_callback(op, [](pa_operation *op, void *userdata){ static_cast<AudioStream*>(userdata)->opEnded(op); }, this); ongoing_ops.emplace(op); } } void AudioStream::opEnded(pa_operation* op) { std::lock_guard lock(mutex_); ongoing_ops.erase(op); pa_operation_unref(op); cond_.notify_all(); } void AudioStream::stateChanged(pa_stream* s) { // UNUSED char str[PA_SAMPLE_SPEC_SNPRINT_MAX]; switch (pa_stream_get_state(s)) { case PA_STREAM_CREATING: JAMI_DBG("Stream is creating..."); break; case PA_STREAM_TERMINATED: JAMI_DBG("Stream is terminating..."); break; case PA_STREAM_READY: JAMI_DBG("Stream successfully created, connected to %s", pa_stream_get_device_name(s)); // JAMI_DBG("maxlength %u", pa_stream_get_buffer_attr(s)->maxlength); // JAMI_DBG("tlength %u", pa_stream_get_buffer_attr(s)->tlength); // JAMI_DBG("prebuf %u", pa_stream_get_buffer_attr(s)->prebuf); // JAMI_DBG("minreq %u", pa_stream_get_buffer_attr(s)->minreq); // JAMI_DBG("fragsize %u", pa_stream_get_buffer_attr(s)->fragsize); // JAMI_DBG("samplespec %s", pa_sample_spec_snprint(str, sizeof(str), pa_stream_get_sample_spec(s))); onReady_(); break; case PA_STREAM_UNCONNECTED: JAMI_DBG("Stream unconnected"); break; case PA_STREAM_FAILED: default: JAMI_ERR("Stream failure: %s", pa_strerror(pa_context_errno(pa_stream_get_context(s)))); break; } } bool AudioStream::isReady() { if (!audiostream_) return false; return pa_stream_get_state(audiostream_) == PA_STREAM_READY; } } // namespace jami
10,049
C++
.cpp
255
29.658824
120
0.577227
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,779
pulselayer.cpp
savoirfairelinux_jami-daemon/src/media/audio/pulseaudio/pulselayer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "compiler_intrinsics.h" #include "audiostream.h" #include "pulselayer.h" #include "audio/ringbufferpool.h" #include "audio/ringbuffer.h" #include "libav_utils.h" #include "logger.h" #include "manager.h" #include <algorithm> // for std::find #include <stdexcept> #include <unistd.h> #include <cstdlib> #include <fstream> #include <cstring> #include <regex> // uncomment to log pulseaudio sink and sources //#define PA_LOG_SINK_SOURCES namespace jami { static const std::regex PA_EC_SUFFIX {"\\.echo-cancel(?:\\..+)?$"}; PulseMainLoopLock::PulseMainLoopLock(pa_threaded_mainloop* loop) : loop_(loop) { pa_threaded_mainloop_lock(loop_); } PulseMainLoopLock::~PulseMainLoopLock() { pa_threaded_mainloop_unlock(loop_); } PulseLayer::PulseLayer(AudioPreference& pref) : AudioLayer(pref) , playback_() , record_() , ringtone_() , mainloop_(pa_threaded_mainloop_new(), pa_threaded_mainloop_free) , preference_(pref) { JAMI_INFO("[audiolayer] created pulseaudio layer"); if (!mainloop_) throw std::runtime_error("Unable to create pulseaudio mainloop"); if (pa_threaded_mainloop_start(mainloop_.get()) < 0) throw std::runtime_error("Failed to start pulseaudio mainloop"); setHasNativeNS(false); PulseMainLoopLock lock(mainloop_.get()); std::unique_ptr<pa_proplist, decltype(pa_proplist_free)&> pl(pa_proplist_new(), pa_proplist_free); pa_proplist_sets(pl.get(), PA_PROP_MEDIA_ROLE, "phone"); context_ = pa_context_new_with_proplist(pa_threaded_mainloop_get_api(mainloop_.get()), PACKAGE_NAME, pl.get()); if (!context_) throw std::runtime_error("Unable to create pulseaudio context"); pa_context_set_state_callback(context_, context_state_callback, this); if (pa_context_connect(context_, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) throw std::runtime_error("Unable to connect pulseaudio context to the server"); // wait until context is ready for (;;) { pa_context_state_t context_state = pa_context_get_state(context_); if (not PA_CONTEXT_IS_GOOD(context_state)) throw std::runtime_error("Pulse audio context is bad"); if (context_state == PA_CONTEXT_READY) break; pa_threaded_mainloop_wait(mainloop_.get()); } } PulseLayer::~PulseLayer() { if (streamStarter_.joinable()) streamStarter_.join(); disconnectAudioStream(); { PulseMainLoopLock lock(mainloop_.get()); pa_context_set_state_callback(context_, NULL, NULL); pa_context_set_subscribe_callback(context_, NULL, NULL); pa_context_disconnect(context_); pa_context_unref(context_); } if (subscribeOp_) pa_operation_unref(subscribeOp_); playbackChanged(false); recordChanged(false); } void PulseLayer::context_state_callback(pa_context* c, void* user_data) { PulseLayer* pulse = static_cast<PulseLayer*>(user_data); if (c and pulse) pulse->contextStateChanged(c); } void PulseLayer::contextStateChanged(pa_context* c) { const pa_subscription_mask_t mask = (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE); switch (pa_context_get_state(c)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: JAMI_DBG("Waiting...."); break; case PA_CONTEXT_READY: JAMI_DBG("Connection to PulseAudio server established"); pa_threaded_mainloop_signal(mainloop_.get(), 0); subscribeOp_ = pa_context_subscribe(c, mask, nullptr, this); pa_context_set_subscribe_callback(c, context_changed_callback, this); updateSinkList(); updateSourceList(); updateServerInfo(); waitForDeviceList(); break; case PA_CONTEXT_TERMINATED: if (subscribeOp_) { pa_operation_unref(subscribeOp_); subscribeOp_ = nullptr; } break; case PA_CONTEXT_FAILED: default: JAMI_ERR("%s", pa_strerror(pa_context_errno(c))); pa_threaded_mainloop_signal(mainloop_.get(), 0); break; } } void PulseLayer::updateSinkList() { std::unique_lock lk(readyMtx_); if (not enumeratingSinks_) { JAMI_DBG("Updating PulseAudio sink list"); enumeratingSinks_ = true; sinkList_.clear(); sinkList_.emplace_back(); sinkList_.front().channel_map.channels = std::min(defaultAudioFormat_.nb_channels, 2u); if (auto op = pa_context_get_sink_info_list(context_, sink_input_info_callback, this)) pa_operation_unref(op); else enumeratingSinks_ = false; } } void PulseLayer::updateSourceList() { std::unique_lock lk(readyMtx_); if (not enumeratingSources_) { JAMI_DBG("Updating PulseAudio source list"); enumeratingSources_ = true; sourceList_.clear(); sourceList_.emplace_back(); sourceList_.front().channel_map.channels = std::min(defaultAudioFormat_.nb_channels, 2u); if (auto op = pa_context_get_source_info_list(context_, source_input_info_callback, this)) pa_operation_unref(op); else enumeratingSources_ = false; } } void PulseLayer::updateServerInfo() { std::unique_lock lk(readyMtx_); if (not gettingServerInfo_) { JAMI_DBG("Updating PulseAudio server infos"); gettingServerInfo_ = true; if (auto op = pa_context_get_server_info(context_, server_info_callback, this)) pa_operation_unref(op); else gettingServerInfo_ = false; } } bool PulseLayer::inSinkList(const std::string& deviceName) { return std::find_if(sinkList_.begin(), sinkList_.end(), PaDeviceInfos::NameComparator(deviceName)) != sinkList_.end(); } bool PulseLayer::inSourceList(const std::string& deviceName) { return std::find_if(sourceList_.begin(), sourceList_.end(), PaDeviceInfos::NameComparator(deviceName)) != sourceList_.end(); } std::vector<std::string> PulseLayer::getCaptureDeviceList() const { std::vector<std::string> names; names.reserve(sourceList_.size()); for (const auto& s : sourceList_) names.emplace_back(s.description); return names; } std::vector<std::string> PulseLayer::getPlaybackDeviceList() const { std::vector<std::string> names; names.reserve(sinkList_.size()); for (const auto& s : sinkList_) names.emplace_back(s.description); return names; } int PulseLayer::getAudioDeviceIndex(const std::string& descr, AudioDeviceType type) const { switch (type) { case AudioDeviceType::PLAYBACK: case AudioDeviceType::RINGTONE: return std::distance(sinkList_.begin(), std::find_if(sinkList_.begin(), sinkList_.end(), PaDeviceInfos::DescriptionComparator(descr))); case AudioDeviceType::CAPTURE: return std::distance(sourceList_.begin(), std::find_if(sourceList_.begin(), sourceList_.end(), PaDeviceInfos::DescriptionComparator(descr))); default: JAMI_ERR("Unexpected device type"); return 0; } } int PulseLayer::getAudioDeviceIndexByName(const std::string& name, AudioDeviceType type) const { if (name.empty()) return 0; switch (type) { case AudioDeviceType::PLAYBACK: case AudioDeviceType::RINGTONE: return std::distance(sinkList_.begin(), std::find_if(sinkList_.begin(), sinkList_.end(), PaDeviceInfos::NameComparator(name))); case AudioDeviceType::CAPTURE: return std::distance(sourceList_.begin(), std::find_if(sourceList_.begin(), sourceList_.end(), PaDeviceInfos::NameComparator(name))); default: JAMI_ERR("Unexpected device type"); return 0; } } bool endsWith(const std::string& str, const std::string& ending) { if (ending.size() >= str.size()) return false; return std::equal(ending.rbegin(), ending.rend(), str.rbegin()); } /** * Find default device for PulseAudio to open, filter monitors and EC. */ const PaDeviceInfos* findBest(const std::vector<PaDeviceInfos>& list) { if (list.empty()) return nullptr; for (const auto& info : list) if (info.monitor_of == PA_INVALID_INDEX) return &info; return &list[0]; } const PaDeviceInfos* PulseLayer::getDeviceInfos(const std::vector<PaDeviceInfos>& list, const std::string& name) const { auto dev_info = std::find_if(list.begin(), list.end(), PaDeviceInfos::NameComparator(name)); if (dev_info == list.end()) { JAMI_WARN("Preferred device %s not found in device list, selecting default %s instead.", name.c_str(), list.front().name.c_str()); return &list.front(); } return &(*dev_info); } std::string PulseLayer::getAudioDeviceName(int index, AudioDeviceType type) const { switch (type) { case AudioDeviceType::PLAYBACK: case AudioDeviceType::RINGTONE: if (index < 0 or static_cast<size_t>(index) >= sinkList_.size()) { JAMI_ERR("Index %d out of range", index); return ""; } return sinkList_[index].name; case AudioDeviceType::CAPTURE: if (index < 0 or static_cast<size_t>(index) >= sourceList_.size()) { JAMI_ERR("Index %d out of range", index); return ""; } return sourceList_[index].name; default: // Should never happen JAMI_ERR("Unexpected type"); return ""; } } void PulseLayer::onStreamReady() { if (--pendingStreams == 0) { JAMI_DBG("All streams ready, starting audio"); // Flush outside the if statement: every time start stream is // called is to notify a new event flushUrgent(); flushMain(); if (playback_) { playback_->start(); playbackChanged(true); } if (ringtone_) { ringtone_->start(); } if (record_) { record_->start(); recordChanged(true); } } } void PulseLayer::createStream(std::unique_ptr<AudioStream>& stream, AudioDeviceType type, const PaDeviceInfos& dev_infos, bool ec, std::function<void(size_t)>&& onData) { if (stream) { JAMI_WARN("Stream already exists"); return; } pendingStreams++; const char* name = type == AudioDeviceType::PLAYBACK ? "Playback" : (type == AudioDeviceType::CAPTURE ? "Record" : (type == AudioDeviceType::RINGTONE ? "Ringtone" : "?")); stream.reset(new AudioStream(context_, mainloop_.get(), name, type, audioFormat_.sample_rate, pulseSampleFormatFromAv(audioFormat_.sampleFormat), dev_infos, ec, std::bind(&PulseLayer::onStreamReady, this), std::move(onData))); } void PulseLayer::disconnectAudioStream() { PulseMainLoopLock lock(mainloop_.get()); playback_.reset(); ringtone_.reset(); record_.reset(); playbackChanged(false); recordChanged(false); pendingStreams = 0; status_ = Status::Idle; startedCv_.notify_all(); } void PulseLayer::startStream(AudioDeviceType type) { waitForDevices(); PulseMainLoopLock lock(mainloop_.get()); bool ec = preference_.getEchoCanceller() == "system" || preference_.getEchoCanceller() == "auto"; // Create Streams if (type == AudioDeviceType::PLAYBACK) { if (auto dev_infos = getDeviceInfos(sinkList_, getPreferredPlaybackDevice())) { createStream(playback_, type, *dev_infos, ec, std::bind(&PulseLayer::writeToSpeaker, this)); } } else if (type == AudioDeviceType::RINGTONE) { if (auto dev_infos = getDeviceInfos(sinkList_, getPreferredRingtoneDevice())) createStream(ringtone_, type, *dev_infos, false, std::bind(&PulseLayer::ringtoneToSpeaker, this)); } else if (type == AudioDeviceType::CAPTURE) { if (auto dev_infos = getDeviceInfos(sourceList_, getPreferredCaptureDevice())) { createStream(record_, type, *dev_infos, ec, std::bind(&PulseLayer::readFromMic, this)); // whenever the stream is moved, it will call this cb record_->setEchoCancelCb([this](bool echoCancel) { setHasNativeAEC(echoCancel); }); } } pa_threaded_mainloop_signal(mainloop_.get(), 0); std::lock_guard lk(mutex_); status_ = Status::Started; startedCv_.notify_all(); } void PulseLayer::stopStream(AudioDeviceType type) { waitForDevices(); PulseMainLoopLock lock(mainloop_.get()); auto& stream(getStream(type)); if (not stream) return; if (not stream->isReady()) pendingStreams--; stream->stop(); stream.reset(); if (type == AudioDeviceType::PLAYBACK || type == AudioDeviceType::ALL) playbackChanged(false); std::lock_guard lk(mutex_); if (not playback_ and not ringtone_ and not record_) { pendingStreams = 0; status_ = Status::Idle; startedCv_.notify_all(); } } void PulseLayer::writeToSpeaker() { if (!playback_ or !playback_->isReady()) return; // available bytes to be written in pulseaudio internal buffer void* data = nullptr; size_t writableBytes = (size_t) -1; int ret = pa_stream_begin_write(playback_->stream(), &data, &writableBytes); if (ret == 0 and data and writableBytes != 0) { writableBytes = std::min(pa_stream_writable_size(playback_->stream()), writableBytes); const auto& buff = getToPlay(playback_->format(), writableBytes / playback_->frameSize()); if (not buff or isPlaybackMuted_) memset(data, 0, writableBytes); else std::memcpy(data, buff->pointer()->data[0], buff->pointer()->nb_samples * playback_->frameSize()); pa_stream_write(playback_->stream(), data, writableBytes, nullptr, 0, PA_SEEK_RELATIVE); } } void PulseLayer::readFromMic() { if (!record_ or !record_->isReady()) return; const char* data = nullptr; size_t bytes; if (pa_stream_peek(record_->stream(), (const void**) &data, &bytes) < 0 or !data) return; if (bytes == 0) return; size_t sample_size = record_->frameSize(); const size_t samples = bytes / sample_size; auto out = std::make_shared<AudioFrame>(record_->format(), samples); if (isCaptureMuted_) libav_utils::fillWithSilence(out->pointer()); else std::memcpy(out->pointer()->data[0], data, bytes); if (pa_stream_drop(record_->stream()) < 0) JAMI_ERR("Capture stream drop failed: %s", pa_strerror(pa_context_errno(context_))); putRecorded(std::move(out)); } void PulseLayer::ringtoneToSpeaker() { if (!ringtone_ or !ringtone_->isReady()) return; void* data = nullptr; size_t writableBytes = (size_t) -1; int ret = pa_stream_begin_write(ringtone_->stream(), &data, &writableBytes); if (ret == 0 and data and writableBytes != 0) { writableBytes = std::min(pa_stream_writable_size(ringtone_->stream()), writableBytes); const auto& buff = getToRing(ringtone_->format(), writableBytes / ringtone_->frameSize()); if (not buff or isRingtoneMuted_) memset(data, 0, writableBytes); else std::memcpy(data, buff->pointer()->data[0], buff->pointer()->nb_samples * ringtone_->frameSize()); pa_stream_write(ringtone_->stream(), data, writableBytes, nullptr, 0, PA_SEEK_RELATIVE); } } std::string stripEchoSufix(const std::string& deviceName) { return std::regex_replace(deviceName, PA_EC_SUFFIX, ""); } void PulseLayer::context_changed_callback(pa_context* c, pa_subscription_event_type_t type, uint32_t idx, void* userdata) { static_cast<PulseLayer*>(userdata)->contextChanged(c, type, idx); } void PulseLayer::contextChanged(pa_context* c UNUSED, pa_subscription_event_type_t type, uint32_t idx UNUSED) { bool reset = false; switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) { case PA_SUBSCRIPTION_EVENT_SINK: switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) { case PA_SUBSCRIPTION_EVENT_NEW: case PA_SUBSCRIPTION_EVENT_REMOVE: updateSinkList(); reset = true; default: break; } break; case PA_SUBSCRIPTION_EVENT_SOURCE: switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) { case PA_SUBSCRIPTION_EVENT_NEW: case PA_SUBSCRIPTION_EVENT_REMOVE: updateSourceList(); reset = true; default: break; } break; default: JAMI_DBG("Unhandled event type 0x%x", type); break; } if (reset) { updateServerInfo(); waitForDeviceList(); } } void PulseLayer::waitForDevices() { std::unique_lock lk(readyMtx_); readyCv_.wait(lk, [this] { return !(enumeratingSinks_ or enumeratingSources_ or gettingServerInfo_); }); } void PulseLayer::waitForDeviceList() { std::unique_lock lock(readyMtx_); if (waitingDeviceList_.exchange(true)) return; if (streamStarter_.joinable()) streamStarter_.join(); streamStarter_ = std::thread([this]() mutable { bool playbackDeviceChanged, recordDeviceChanged; waitForDevices(); waitingDeviceList_ = false; // If a current device changed, restart streams devicesChanged(); auto playbackInfo = getDeviceInfos(sinkList_, getPreferredPlaybackDevice()); playbackDeviceChanged = playback_ and (!playbackInfo->name.empty() and playbackInfo->name != stripEchoSufix(playback_->getDeviceName())); auto recordInfo = getDeviceInfos(sourceList_, getPreferredCaptureDevice()); recordDeviceChanged = record_ and (!recordInfo->name.empty() and recordInfo->name != stripEchoSufix(record_->getDeviceName())); if (status_ != Status::Started) return; if (playbackDeviceChanged) { JAMI_WARN("Playback devices changed, restarting streams."); stopStream(AudioDeviceType::PLAYBACK); startStream(AudioDeviceType::PLAYBACK); } if (recordDeviceChanged) { JAMI_WARN("Record devices changed, restarting streams."); stopStream(AudioDeviceType::CAPTURE); startStream(AudioDeviceType::CAPTURE); } }); } void PulseLayer::server_info_callback(pa_context*, const pa_server_info* i, void* userdata) { if (!i) return; char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; JAMI_DBG("PulseAudio server info:\n" " Server name: %s\n" " Server version: %s\n" " Default Sink %s\n" " Default Source %s\n" " Default Sample Specification: %s\n" " Default Channel Map: %s\n", i->server_name, i->server_version, i->default_sink_name, i->default_source_name, pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map)); PulseLayer* context = static_cast<PulseLayer*>(userdata); std::lock_guard lk(context->readyMtx_); context->defaultSink_ = {}; context->defaultSource_ = {}; context->defaultAudioFormat_ = { i->sample_spec.rate, i->sample_spec.channels, sampleFormatFromPulse(i->sample_spec.format) }; { std::lock_guard lk(context->mutex_); context->hardwareFormatAvailable(context->defaultAudioFormat_); } /*if (not context->sinkList_.empty()) context->sinkList_.front().channel_map.channels = std::min(i->sample_spec.channels, (uint8_t) 2); if (not context->sourceList_.empty()) context->sourceList_.front().channel_map.channels = std::min(i->sample_spec.channels, (uint8_t) 2);*/ context->gettingServerInfo_ = false; context->readyCv_.notify_all(); } void PulseLayer::source_input_info_callback(pa_context* c UNUSED, const pa_source_info* i, int eol, void* userdata) { PulseLayer* context = static_cast<PulseLayer*>(userdata); if (eol) { std::lock_guard lk(context->readyMtx_); context->enumeratingSources_ = false; context->readyCv_.notify_all(); return; } #ifdef PA_LOG_SINK_SOURCES char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; JAMI_DBG("Source %u\n" " Name: %s\n" " Driver: %s\n" " Description: %s\n" " Sample Specification: %s\n" " Channel Map: %s\n" " Owner Module: %u\n" " Volume: %s\n" " Monitor if Sink: %u\n" " Latency: %0.0f usec\n" " Flags: %s%s%s\n", i->index, i->name, i->driver, i->description, pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), i->owner_module, i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), i->monitor_of_sink, (double) i->latency, i->flags & PA_SOURCE_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", i->flags & PA_SOURCE_LATENCY ? "LATENCY " : "", i->flags & PA_SOURCE_HARDWARE ? "HARDWARE" : ""); #endif if (not context->inSourceList(i->name)) { context->sourceList_.emplace_back(*i); } } void PulseLayer::sink_input_info_callback(pa_context* c UNUSED, const pa_sink_info* i, int eol, void* userdata) { PulseLayer* context = static_cast<PulseLayer*>(userdata); std::lock_guard lk(context->readyMtx_); if (eol) { context->enumeratingSinks_ = false; context->readyCv_.notify_all(); return; } #ifdef PA_LOG_SINK_SOURCES char s[PA_SAMPLE_SPEC_SNPRINT_MAX], cv[PA_CVOLUME_SNPRINT_MAX], cm[PA_CHANNEL_MAP_SNPRINT_MAX]; JAMI_DBG("Sink %u\n" " Name: %s\n" " Driver: %s\n" " Description: %s\n" " Sample Specification: %s\n" " Channel Map: %s\n" " Owner Module: %u\n" " Volume: %s\n" " Monitor Source: %u\n" " Latency: %0.0f usec\n" " Flags: %s%s%s\n", i->index, i->name, i->driver, i->description, pa_sample_spec_snprint(s, sizeof(s), &i->sample_spec), pa_channel_map_snprint(cm, sizeof(cm), &i->channel_map), i->owner_module, i->mute ? "muted" : pa_cvolume_snprint(cv, sizeof(cv), &i->volume), i->monitor_source, static_cast<double>(i->latency), i->flags & PA_SINK_HW_VOLUME_CTRL ? "HW_VOLUME_CTRL " : "", i->flags & PA_SINK_LATENCY ? "LATENCY " : "", i->flags & PA_SINK_HARDWARE ? "HARDWARE" : ""); #endif if (not context->inSinkList(i->name)) { context->sinkList_.emplace_back(*i); } } void PulseLayer::updatePreference(AudioPreference& preference, int index, AudioDeviceType type) { const std::string devName(getAudioDeviceName(index, type)); switch (type) { case AudioDeviceType::PLAYBACK: JAMI_DBG("setting %s for playback", devName.c_str()); preference.setPulseDevicePlayback(devName); break; case AudioDeviceType::CAPTURE: JAMI_DBG("setting %s for capture", devName.c_str()); preference.setPulseDeviceRecord(devName); break; case AudioDeviceType::RINGTONE: JAMI_DBG("setting %s for ringer", devName.c_str()); preference.setPulseDeviceRingtone(devName); break; default: break; } } int PulseLayer::getIndexCapture() const { return getAudioDeviceIndexByName(preference_.getPulseDeviceRecord(), AudioDeviceType::CAPTURE); } int PulseLayer::getIndexPlayback() const { return getAudioDeviceIndexByName(preference_.getPulseDevicePlayback(), AudioDeviceType::PLAYBACK); } int PulseLayer::getIndexRingtone() const { return getAudioDeviceIndexByName(preference_.getPulseDeviceRingtone(), AudioDeviceType::RINGTONE); } std::string PulseLayer::getPreferredPlaybackDevice() const { const std::string& device(preference_.getPulseDevicePlayback()); return stripEchoSufix(device.empty() ? defaultSink_ : device); } std::string PulseLayer::getPreferredRingtoneDevice() const { const std::string& device(preference_.getPulseDeviceRingtone()); return stripEchoSufix(device.empty() ? defaultSink_ : device); } std::string PulseLayer::getPreferredCaptureDevice() const { const std::string& device(preference_.getPulseDeviceRecord()); return stripEchoSufix(device.empty() ? defaultSource_ : device); } } // namespace jami
27,945
C++
.cpp
776
27.148196
101
0.590617
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,780
alsalayer.cpp
savoirfairelinux_jami-daemon/src/media/audio/alsa/alsalayer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "alsalayer.h" #include "logger.h" #include "manager.h" #include "noncopyable.h" #include "client/ring_signal.h" #include "audio/ringbufferpool.h" #include "audio/ringbuffer.h" #include "audio/audioloop.h" #include "libav_utils.h" #include <fmt/core.h> #include <thread> #include <atomic> #include <chrono> namespace jami { AlsaLayer::AlsaLayer(const AudioPreference& pref) : AudioLayer(pref) , indexIn_(pref.getAlsaCardin()) , indexOut_(pref.getAlsaCardout()) , indexRing_(pref.getAlsaCardRingtone()) , audioPlugin_(pref.getAlsaPlugin()) { setHasNativeAEC(false); setHasNativeNS(false); } AlsaLayer::~AlsaLayer() { status_ = Status::Idle; stopThread(); /* Then close the audio devices */ closeCaptureStream(); closePlaybackStream(); closeRingtoneStream(); } /** * Reimplementation of run() */ void AlsaLayer::run() { if (playbackHandle_) playbackChanged(true); if (captureHandle_) recordChanged(true); while (status_ == Status::Started and running_) { playback(); ringtone(); capture(); } playbackChanged(false); recordChanged(false); } // Retry approach taken from pa_linux_alsa.c, part of PortAudio bool AlsaLayer::openDevice(snd_pcm_t** pcm, const std::string& dev, snd_pcm_stream_t stream, AudioFormat& format) { JAMI_DBG("Alsa: Opening %s device '%s'", (stream == SND_PCM_STREAM_CAPTURE) ? "capture" : "playback", dev.c_str()); static const int MAX_RETRIES = 10; // times of 100ms int err, tries = 0; do { err = snd_pcm_open(pcm, dev.c_str(), stream, 0); // Retry if busy, since dmix plugin may not have released the device yet if (err == -EBUSY) { // We're called in audioThread_ context, so if exit is requested // force return now std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } while (err == -EBUSY and ++tries <= MAX_RETRIES); if (err < 0) { JAMI_ERR("Alsa: Unable to open %s device %s : %s", (stream == SND_PCM_STREAM_CAPTURE) ? "capture" : (stream == SND_PCM_STREAM_PLAYBACK) ? "playback" : "ringtone", dev.c_str(), snd_strerror(err)); return false; } if (!alsa_set_params(*pcm, format)) { snd_pcm_close(*pcm); return false; } return true; } void AlsaLayer::startStream(AudioDeviceType type) { std::unique_lock lk(mutex_); status_ = Status::Starting; stopThread(); bool dsnop = audioPlugin_ == PCM_DMIX_DSNOOP; if (type == AudioDeviceType::PLAYBACK and not is_playback_open_) { is_playback_open_ = openDevice(&playbackHandle_, buildDeviceTopo(dsnop ? PCM_DMIX : audioPlugin_, indexOut_), SND_PCM_STREAM_PLAYBACK, audioFormat_); if (not is_playback_open_) emitSignal<libjami::ConfigurationSignal::Error>(ALSA_PLAYBACK_DEVICE); hardwareFormatAvailable(getFormat()); startPlaybackStream(); } if (type == AudioDeviceType::RINGTONE and getIndexPlayback() != getIndexRingtone() and not ringtoneHandle_) { if (!openDevice(&ringtoneHandle_, buildDeviceTopo(dsnop ? PCM_DMIX : audioPlugin_, indexRing_), SND_PCM_STREAM_PLAYBACK, audioFormat_)) emitSignal<libjami::ConfigurationSignal::Error>(ALSA_PLAYBACK_DEVICE); } if (type == AudioDeviceType::CAPTURE and not is_capture_open_) { is_capture_open_ = openDevice(&captureHandle_, buildDeviceTopo(dsnop ? PCM_DSNOOP : audioPlugin_, indexIn_), SND_PCM_STREAM_CAPTURE, audioInputFormat_); if (not is_capture_open_) emitSignal<libjami::ConfigurationSignal::Error>(ALSA_CAPTURE_DEVICE); prepareCaptureStream(); startCaptureStream(); } status_ = Status::Started; startThread(); } void AlsaLayer::stopStream(AudioDeviceType stream) { std::unique_lock lk(mutex_); stopThread(); if (stream == AudioDeviceType::CAPTURE && is_capture_open_) { closeCaptureStream(); } if (stream == AudioDeviceType::PLAYBACK && is_playback_open_) { closePlaybackStream(); flushUrgent(); flushMain(); } if (stream == AudioDeviceType::RINGTONE and ringtoneHandle_) { closeRingtoneStream(); } if (is_capture_open_ or is_playback_open_ or ringtoneHandle_) { startThread(); } else { status_ = Status::Idle; } } void AlsaLayer::startThread() { running_ = true; audioThread_ = std::thread(&AlsaLayer::run, this); } void AlsaLayer::stopThread() { running_ = false; if (audioThread_.joinable()) audioThread_.join(); } /* * GCC extension : statement expression * * ALSA_CALL(function_call, error_string) will: * call the function * display an error if the function failed * return the function return value */ #define ALSA_CALL(call, error) \ ({ \ int err_code = call; \ if (err_code < 0) \ JAMI_ERR(error ": %s", snd_strerror(err_code)); \ err_code; \ }) void AlsaLayer::stopCaptureStream() { if (captureHandle_ && ALSA_CALL(snd_pcm_drop(captureHandle_), "Unable to stop capture") >= 0) { is_capture_running_ = false; is_capture_prepared_ = false; } } void AlsaLayer::closeCaptureStream() { if (is_capture_prepared_ and is_capture_running_) stopCaptureStream(); JAMI_DBG("Alsa: Closing capture stream"); if (is_capture_open_ && ALSA_CALL(snd_pcm_close(captureHandle_), "Unable to close capture") >= 0) { is_capture_open_ = false; captureHandle_ = nullptr; } } void AlsaLayer::startCaptureStream() { if (captureHandle_ and not is_capture_running_) if (ALSA_CALL(snd_pcm_start(captureHandle_), "Unable to start capture") >= 0) is_capture_running_ = true; } void AlsaLayer::stopPlaybackStream() { if (playbackHandle_ and is_playback_running_) { if (ALSA_CALL(snd_pcm_drop(playbackHandle_), "Unable to stop playback") >= 0) { is_playback_running_ = false; } } } void AlsaLayer::closePlaybackStream() { if (is_playback_running_) stopPlaybackStream(); if (is_playback_open_) { JAMI_DBG("Alsa: Closing playback stream"); if (ALSA_CALL(snd_pcm_close(playbackHandle_), "Coulnd't close playback") >= 0) is_playback_open_ = false; playbackHandle_ = nullptr; } } void AlsaLayer::closeRingtoneStream() { if (ringtoneHandle_) { ALSA_CALL(snd_pcm_drop(ringtoneHandle_), "Unable to stop ringtone"); ALSA_CALL(snd_pcm_close(ringtoneHandle_), "Unable to close ringtone"); ringtoneHandle_ = nullptr; } } void AlsaLayer::startPlaybackStream() { is_playback_running_ = true; } void AlsaLayer::prepareCaptureStream() { if (is_capture_open_ and not is_capture_prepared_) if (ALSA_CALL(snd_pcm_prepare(captureHandle_), "Unable to prepare capture") >= 0) is_capture_prepared_ = true; } bool AlsaLayer::alsa_set_params(snd_pcm_t* pcm_handle, AudioFormat& format) { #define TRY(call, error) \ do { \ if (ALSA_CALL(call, error) < 0) \ return false; \ } while (0) snd_pcm_hw_params_t* hwparams; snd_pcm_hw_params_alloca(&hwparams); const unsigned RING_ALSA_PERIOD_SIZE = 160; const unsigned RING_ALSA_NB_PERIOD = 8; const unsigned RING_ALSA_BUFFER_SIZE = RING_ALSA_PERIOD_SIZE * RING_ALSA_NB_PERIOD; snd_pcm_uframes_t period_size = RING_ALSA_PERIOD_SIZE; snd_pcm_uframes_t buffer_size = RING_ALSA_BUFFER_SIZE; unsigned int periods = RING_ALSA_NB_PERIOD; snd_pcm_uframes_t period_size_min = 0; snd_pcm_uframes_t period_size_max = 0; snd_pcm_uframes_t buffer_size_min = 0; snd_pcm_uframes_t buffer_size_max = 0; #define HW pcm_handle, hwparams /* hardware parameters */ TRY(snd_pcm_hw_params_any(HW), "hwparams init"); TRY(snd_pcm_hw_params_set_access(HW, SND_PCM_ACCESS_RW_INTERLEAVED), "access type"); TRY(snd_pcm_hw_params_set_format(HW, SND_PCM_FORMAT_S16_LE), "sample format"); TRY(snd_pcm_hw_params_set_rate_resample(HW, 0), "hardware sample rate"); /* prevent software resampling */ TRY(snd_pcm_hw_params_set_rate_near(HW, &format.sample_rate, nullptr), "sample rate"); // TODO: use snd_pcm_query_chmaps or similar to get hardware channel num audioFormat_.nb_channels = 2; format.nb_channels = 2; TRY(snd_pcm_hw_params_set_channels_near(HW, &format.nb_channels), "channel count"); snd_pcm_hw_params_get_buffer_size_min(hwparams, &buffer_size_min); snd_pcm_hw_params_get_buffer_size_max(hwparams, &buffer_size_max); snd_pcm_hw_params_get_period_size_min(hwparams, &period_size_min, nullptr); snd_pcm_hw_params_get_period_size_max(hwparams, &period_size_max, nullptr); JAMI_DBG("Buffer size range from %lu to %lu", buffer_size_min, buffer_size_max); JAMI_DBG("Period size range from %lu to %lu", period_size_min, period_size_max); buffer_size = buffer_size > buffer_size_max ? buffer_size_max : buffer_size; buffer_size = buffer_size < buffer_size_min ? buffer_size_min : buffer_size; period_size = period_size > period_size_max ? period_size_max : period_size; period_size = period_size < period_size_min ? period_size_min : period_size; TRY(snd_pcm_hw_params_set_buffer_size_near(HW, &buffer_size), "Unable to set buffer size for playback"); TRY(snd_pcm_hw_params_set_period_size_near(HW, &period_size, nullptr), "Unable to set period size for playback"); TRY(snd_pcm_hw_params_set_periods_near(HW, &periods, nullptr), "Unable to set number of periods for playback"); TRY(snd_pcm_hw_params(HW), "hwparams"); snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size); snd_pcm_hw_params_get_period_size(hwparams, &period_size, nullptr); snd_pcm_hw_params_get_rate(hwparams, &format.sample_rate, nullptr); snd_pcm_hw_params_get_channels(hwparams, &format.nb_channels); JAMI_DBG("Was set period_size = %lu", period_size); JAMI_DBG("Was set buffer_size = %lu", buffer_size); if (2 * period_size > buffer_size) { JAMI_ERR("buffer to small, unable to use"); return false; } #undef HW JAMI_DBG("%s using format %s", (snd_pcm_stream(pcm_handle) == SND_PCM_STREAM_PLAYBACK) ? "playback" : "capture", format.toString().c_str()); snd_pcm_sw_params_t* swparams = nullptr; snd_pcm_sw_params_alloca(&swparams); #define SW pcm_handle, swparams /* software parameters */ snd_pcm_sw_params_current(SW); TRY(snd_pcm_sw_params_set_start_threshold(SW, period_size * 2), "start threshold"); TRY(snd_pcm_sw_params(SW), "sw parameters"); #undef SW return true; #undef TRY } // TODO first frame causes broken pipe (underrun) because not enough data is sent // we should wait until the handle is ready void AlsaLayer::write(const AudioFrame& buffer, snd_pcm_t* handle) { int err = snd_pcm_writei(handle, (const void*) buffer.pointer()->data[0], buffer.pointer()->nb_samples); if (err < 0) snd_pcm_recover(handle, err, 0); if (err >= 0) return; switch (err) { case -EPIPE: case -ESTRPIPE: case -EIO: { snd_pcm_status_t* status; snd_pcm_status_alloca(&status); if (ALSA_CALL(snd_pcm_status(handle, status), "Unable to get playback handle status") >= 0) if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) { stopPlaybackStream(); startPlaybackStream(); } ALSA_CALL(snd_pcm_writei(handle, (const void*) buffer.pointer()->data[0], buffer.pointer()->nb_samples), "XRUN handling failed"); break; } case -EBADFD: { snd_pcm_status_t* status; snd_pcm_status_alloca(&status); if (ALSA_CALL(snd_pcm_status(handle, status), "Unable to get playback handle status") >= 0) { if (snd_pcm_status_get_state(status) == SND_PCM_STATE_SETUP) { JAMI_ERR("Writing in state SND_PCM_STATE_SETUP, should be " "SND_PCM_STATE_PREPARED or SND_PCM_STATE_RUNNING"); int error = snd_pcm_prepare(handle); if (error < 0) { JAMI_ERR("Failed to prepare handle: %s", snd_strerror(error)); stopPlaybackStream(); } } } break; } default: JAMI_ERR("Unknown write error, dropping frames: %s", snd_strerror(err)); stopPlaybackStream(); break; } } std::unique_ptr<AudioFrame> AlsaLayer::read(unsigned frames) { if (snd_pcm_state(captureHandle_) == SND_PCM_STATE_XRUN) { prepareCaptureStream(); startCaptureStream(); } auto ret = std::make_unique<AudioFrame>(audioInputFormat_, frames); int err = snd_pcm_readi(captureHandle_, ret->pointer()->data[0], frames); if (err >= 0) { ret->pointer()->nb_samples = err; return ret; } switch (err) { case -EPIPE: case -ESTRPIPE: case -EIO: { snd_pcm_status_t* status; snd_pcm_status_alloca(&status); if (ALSA_CALL(snd_pcm_status(captureHandle_, status), "Get status failed") >= 0) if (snd_pcm_status_get_state(status) == SND_PCM_STATE_XRUN) { stopCaptureStream(); prepareCaptureStream(); startCaptureStream(); } JAMI_ERR("XRUN capture ignored (%s)", snd_strerror(err)); break; } case -EPERM: JAMI_ERR("Unable to capture, EPERM (%s)", snd_strerror(err)); prepareCaptureStream(); startCaptureStream(); break; } return {}; } std::string AlsaLayer::buildDeviceTopo(const std::string& plugin, int card) { if (plugin == PCM_DEFAULT) return plugin; return fmt::format("{}:{}", plugin, card); } static bool safeUpdate(snd_pcm_t* handle, long& samples) { samples = snd_pcm_avail_update(handle); if (samples < 0) { samples = snd_pcm_recover(handle, samples, 0); if (samples < 0) { JAMI_ERR("Got unrecoverable error from snd_pcm_avail_update: %s", snd_strerror(samples)); return false; } } return true; } static std::vector<std::string> getValues(const std::vector<HwIDPair>& deviceMap) { std::vector<std::string> audioDeviceList; audioDeviceList.reserve(deviceMap.size()); for (const auto& dev : deviceMap) audioDeviceList.push_back(dev.second); return audioDeviceList; } std::vector<std::string> AlsaLayer::getCaptureDeviceList() const { return getValues(getAudioDeviceIndexMap(true)); } std::vector<std::string> AlsaLayer::getPlaybackDeviceList() const { return getValues(getAudioDeviceIndexMap(false)); } std::vector<HwIDPair> AlsaLayer::getAudioDeviceIndexMap(bool getCapture) const { snd_ctl_t* handle; snd_ctl_card_info_t* info; snd_pcm_info_t* pcminfo; snd_ctl_card_info_alloca(&info); snd_pcm_info_alloca(&pcminfo); int numCard = -1; std::vector<HwIDPair> audioDevice; if (snd_card_next(&numCard) < 0 || numCard < 0) return audioDevice; do { std::string name = fmt::format("hw:{}", numCard); if (snd_ctl_open(&handle, name.c_str(), 0) == 0) { if (snd_ctl_card_info(handle, info) == 0) { snd_pcm_info_set_device(pcminfo, 0); snd_pcm_info_set_stream(pcminfo, getCapture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK); int err; if ((err = snd_ctl_pcm_info(handle, pcminfo)) < 0) { JAMI_WARN("Unable to get info for %s %s: %s", getCapture ? "capture device" : "playback device", name.c_str(), snd_strerror(err)); } else { JAMI_DBG("card %i : %s [%s]", numCard, snd_ctl_card_info_get_id(info), snd_ctl_card_info_get_name(info)); std::string description = snd_ctl_card_info_get_name(info); description.append(" - "); description.append(snd_pcm_info_get_name(pcminfo)); // The number of the sound card is associated with a string description audioDevice.emplace_back(numCard, std::move(description)); } } snd_ctl_close(handle); } } while (snd_card_next(&numCard) >= 0 && numCard >= 0); return audioDevice; } bool AlsaLayer::soundCardIndexExists(int card, AudioDeviceType stream) { std::string name = fmt::format("hw:{}", card); snd_ctl_t* handle; if (snd_ctl_open(&handle, name.c_str(), 0) != 0) return false; snd_pcm_info_t* pcminfo; snd_pcm_info_alloca(&pcminfo); snd_pcm_info_set_stream(pcminfo, stream == AudioDeviceType::PLAYBACK ? SND_PCM_STREAM_PLAYBACK : SND_PCM_STREAM_CAPTURE); bool ret = snd_ctl_pcm_info(handle, pcminfo) >= 0; snd_ctl_close(handle); return ret; } int AlsaLayer::getAudioDeviceIndex(const std::string& description, AudioDeviceType type) const { std::vector<HwIDPair> devices = getAudioDeviceIndexMap(type == AudioDeviceType::CAPTURE); for (const auto& dev : devices) if (dev.second == description) return dev.first; // else return the default one return 0; } std::string AlsaLayer::getAudioDeviceName(int index, AudioDeviceType type) const { // a bit ugly and wrong.. i do not know how to implement it better in alsalayer. // in addition, for now it is used in pulselayer only due to alsa and pulse layers api // differences. but after some tweaking in alsalayer, it could be used in it too. switch (type) { case AudioDeviceType::PLAYBACK: case AudioDeviceType::RINGTONE: return getPlaybackDeviceList().at(index); case AudioDeviceType::CAPTURE: return getCaptureDeviceList().at(index); default: // Should never happen JAMI_ERR("Unexpected type"); return ""; } } void AlsaLayer::capture() { if (!captureHandle_ or !is_capture_running_) return; snd_pcm_wait(captureHandle_, 10); int toGetFrames = snd_pcm_avail_update(captureHandle_); if (toGetFrames < 0) JAMI_ERR("Audio: Mic error: %s", snd_strerror(toGetFrames)); if (toGetFrames <= 0) return; const int framesPerBufferAlsa = 2048; toGetFrames = std::min(framesPerBufferAlsa, toGetFrames); if (auto r = read(toGetFrames)) { putRecorded(std::move(r)); } else JAMI_ERR("ALSA MIC : Unable to read!"); } void AlsaLayer::playback() { if (!playbackHandle_) return; snd_pcm_wait(playbackHandle_, 20); long maxFrames = 0; if (not safeUpdate(playbackHandle_, maxFrames)) return; if (auto toPlay = getToPlay(audioFormat_, maxFrames)) { write(*toPlay, playbackHandle_); } } void AlsaLayer::ringtone() { if (!ringtoneHandle_) return; long ringtoneAvailFrames = 0; if (not safeUpdate(ringtoneHandle_, ringtoneAvailFrames)) return; if (auto toRing = getToRing(audioFormat_, ringtoneAvailFrames)) { write(*toRing, ringtoneHandle_); } } void AlsaLayer::updatePreference(AudioPreference& preference, int index, AudioDeviceType type) { switch (type) { case AudioDeviceType::PLAYBACK: preference.setAlsaCardout(index); break; case AudioDeviceType::CAPTURE: preference.setAlsaCardin(index); break; case AudioDeviceType::RINGTONE: preference.setAlsaCardRingtone(index); break; default: break; } } } // namespace jami
21,450
C++
.cpp
606
28.160066
101
0.620946
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,781
dtmfgenerator.cpp
savoirfairelinux_jami-daemon/src/media/audio/sound/dtmfgenerator.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "dtmfgenerator.h" #include "libav_deps.h" #include <cmath> #include <cassert> #include <ciso646> // fix windows compiler bug namespace jami { /* * Tone frequencies */ const DTMFGenerator::DTMFTone DTMFGenerator::tones_[] = {{'0', 941, 1336}, {'1', 697, 1209}, {'2', 697, 1336}, {'3', 697, 1477}, {'4', 770, 1209}, {'5', 770, 1336}, {'6', 770, 1477}, {'7', 852, 1209}, {'8', 852, 1336}, {'9', 852, 1477}, {'A', 697, 1633}, {'B', 770, 1633}, {'C', 852, 1633}, {'D', 941, 1633}, {'*', 941, 1209}, {'#', 941, 1477}}; /* * Initialize the generator */ DTMFGenerator::DTMFGenerator(unsigned int sampleRate, AVSampleFormat sampleFormat) : state() , sampleRate_(sampleRate) , tone_("", sampleRate, sampleFormat) { state.offset = 0; state.sample = 0; for (int i = 0; i < NUM_TONES; i++) toneBuffers_[i] = fillToneBuffer(i); } DTMFGenerator::~DTMFGenerator() {} using std::vector; void DTMFGenerator::getSamples(AVFrame* frame, unsigned char code) { code = toupper(code); if (code >= '0' and code <= '9') state.sample = toneBuffers_[code - '0'].get(); else if (code >= 'A' and code <= 'D') state.sample = toneBuffers_[code - 'A' + 10].get(); else { switch (code) { case '*': state.sample = toneBuffers_[NUM_TONES - 2].get(); break; case '#': state.sample = toneBuffers_[NUM_TONES - 1].get(); break; default: throw DTMFException("Invalid code"); break; } } av_samples_copy(frame->data, state.sample->data, 0, state.offset, frame->nb_samples, frame->ch_layout.nb_channels, (AVSampleFormat)frame->format); state.offset = frame->nb_samples % sampleRate_; } /* * Get next n samples (continues where previous call to * genSample or genNextSamples stopped */ void DTMFGenerator::getNextSamples(AVFrame* frame) { if (state.sample == 0) throw DTMFException("DTMF generator not initialized"); av_samples_copy(frame->data, state.sample->data, 0, state.offset, frame->nb_samples, frame->ch_layout.nb_channels, (AVSampleFormat)frame->format); state.offset = (state.offset + frame->nb_samples) % sampleRate_; } libjami::FrameBuffer DTMFGenerator::fillToneBuffer(int index) { assert(index >= 0 and index < NUM_TONES); libjami::FrameBuffer ptr(av_frame_alloc()); ptr->nb_samples = sampleRate_; ptr->format = tone_.getFormat().sampleFormat; ptr->sample_rate = sampleRate_; ptr->channel_layout = AV_CH_LAYOUT_MONO; av_channel_layout_from_mask(&ptr->ch_layout, AV_CH_LAYOUT_MONO); av_frame_get_buffer(ptr.get(), 0); tone_.genSin(ptr.get(), 0, ptr->nb_samples, tones_[index].higher, tones_[index].lower); return ptr; } } // namespace jami
4,361
C++
.cpp
104
29.951923
150
0.528066
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,782
audiofile.cpp
savoirfairelinux_jami-daemon/src/media/audio/sound/audiofile.cpp
/* Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * Inspired by ringbuffer of Audacity Project * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <fstream> #include <cmath> #include <cstring> #include <vector> #include <climits> #include "libav_deps.h" #include "audiofile.h" #include "audio/resampler.h" #include "manager.h" #include "media_decoder.h" #include "client/ring_signal.h" #include "logger.h" namespace jami { void AudioFile::onBufferFinish() { if (buffer_->sample_rate == 0) { JAMI_ERR("Error unable to update playback slider, sampling rate is 0"); return; } // We want to send values in milisecond if ((updatePlaybackScale_ % 5) == 0) emitSignal<libjami::CallSignal::UpdatePlaybackScale>(filepath_, (unsigned) (1000lu * pos_ / buffer_->sample_rate), (unsigned) (1000lu * buffer_->nb_samples / buffer_->sample_rate)); updatePlaybackScale_++; } AudioFile::AudioFile(const std::string& fileName, unsigned int sampleRate, AVSampleFormat sampleFormat) : AudioLoop(AudioFormat(sampleRate, 1, sampleFormat)) , filepath_(fileName) , updatePlaybackScale_(0) { std::list<std::shared_ptr<AudioFrame>> buf; size_t total_samples = 0; auto start = std::chrono::steady_clock::now(); Resampler r {}; auto decoder = std::make_unique<MediaDecoder>( [&r, this, &buf, &total_samples](const std::shared_ptr<MediaFrame>& frame) mutable { auto resampled = r.resample(std::static_pointer_cast<AudioFrame>(frame), format_); total_samples += resampled->getFrameSize(); buf.emplace_back(std::move(resampled)); }); DeviceParams dev; dev.input = fileName; dev.name = fileName; if (decoder->openInput(dev) < 0) throw AudioFileException("Unable to open file: " + fileName); if (decoder->setupAudio() < 0) throw AudioFileException("Decoder setup failed: " + fileName); while (decoder->decode() != MediaDemuxer::Status::EndOfFile) ; buffer_->nb_samples = total_samples; buffer_->format = format_.sampleFormat; buffer_->sample_rate = format_.sample_rate; av_channel_layout_default(&buffer_->ch_layout, format_.nb_channels); av_frame_get_buffer(buffer_.get(), 0); size_t outPos = 0; for (auto& frame : buf) { av_samples_copy(buffer_->data, frame->pointer()->data, outPos, 0, frame->getFrameSize(), format_.nb_channels, format_.sampleFormat); outPos += frame->getFrameSize(); } auto end = std::chrono::steady_clock::now(); auto audioDuration = std::chrono::duration<double>(total_samples/(double)format_.sample_rate); JAMI_LOG("AudioFile: loaded {} samples ({}) as {} in {} from {:s}", total_samples, audioDuration, format_.toString(), dht::print_duration(end-start), fileName); } } // namespace jami
3,678
C++
.cpp
86
37.186047
140
0.671045
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,783
tone.cpp
savoirfairelinux_jami-daemon/src/media/audio/sound/tone.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * Inspired by ringbuffer of Audacity Project * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "tone.h" #include "logger.h" #include "ring_types.h" #include "string_utils.h" #include <vector> #include <cmath> #include <cstdlib> namespace jami { Tone::Tone(std::string_view definition, unsigned int sampleRate, AVSampleFormat sampleFormat) : AudioLoop(AudioFormat(sampleRate, 1, sampleFormat)) { genBuffer(definition); // allocate memory with definition parameter } struct ParsedDefinition { unsigned total_samples; std::vector<std::tuple<unsigned, unsigned, unsigned>> frequencies; }; ParsedDefinition parseDefinition(std::string_view definition, unsigned sampleRate) { ParsedDefinition parsed; parsed.total_samples = 0; std::string_view s; // portion of frequencyq while (getline_full(definition, s, ',')) { // Sample string: "350+440" or "350+440/2000,244+655/2000" unsigned low, high, time; size_t count; // number of int for one sequence // The 1st frequency is before the first + or the / size_t pos_plus = s.find('+'); size_t pos_slash = s.find('/'); size_t len = s.length(); size_t endfrequency = 0; if (pos_slash == std::string::npos) { time = 0; endfrequency = len; } else { time = to_int<unsigned>(s.substr(pos_slash + 1, len - pos_slash - 1), 0); endfrequency = pos_slash; } // without a plus = 1 frequency if (pos_plus == std::string::npos) { low = to_int<unsigned>(s.substr(0, endfrequency), 0); high = 0; } else { low = to_int<unsigned>(s.substr(0, pos_plus), 0); high = to_int<unsigned>(s.substr(pos_plus + 1, endfrequency - pos_plus - 1), 0); } // If there is time or if it's unlimited if (time == 0) count = sampleRate; else count = (sampleRate * time) / 1000; parsed.frequencies.emplace_back(low, high, count); parsed.total_samples += count; } return parsed; } void Tone::genBuffer(std::string_view definition) { if (definition.empty()) return; auto [total_samples, frequencies] = parseDefinition(definition, format_.sample_rate); buffer_->nb_samples = total_samples; buffer_->format = format_.sampleFormat; buffer_->sample_rate = format_.sample_rate; av_channel_layout_default(&buffer_->ch_layout, format_.nb_channels); av_frame_get_buffer(buffer_.get(), 0); size_t outPos = 0; for (auto& [low, high, count] : frequencies) { genSin(buffer_.get(), outPos, count, low, high); outPos += count; } } void Tone::genSin(AVFrame* buffer, size_t outPos, unsigned nb_samples, unsigned lowFrequency, unsigned highFrequency) { static constexpr auto PI_2 = 3.141592653589793238462643383279502884L * 2.0L; const double sr = (double) buffer->sample_rate; const double dx_h = sr ? PI_2 * lowFrequency / sr : 0.0; const double dx_l = sr ? PI_2 * highFrequency / sr : 0.0; static constexpr double DATA_AMPLITUDE_S16 = 2048; static constexpr double DATA_AMPLITUDE_FLT = 0.0625; if (buffer->format == AV_SAMPLE_FMT_S16 || buffer->format == AV_SAMPLE_FMT_S16P) { int16_t* ptr = ((int16_t*) buffer->data[0]) + outPos; for (size_t t = 0; t < nb_samples; t++) { ptr[t] = DATA_AMPLITUDE_S16 * (sin(t * dx_h) + sin(t * dx_l)); } } else if (buffer->format == AV_SAMPLE_FMT_FLT || buffer->format == AV_SAMPLE_FMT_FLTP) { float* ptr = ((float*) buffer->data[0]) + outPos; for (size_t t = 0; t < nb_samples; t++) { ptr[t] = (sin(t * dx_h) + sin(t * dx_l)) * DATA_AMPLITUDE_FLT; } } else { JAMI_ERROR("Unsupported sample format: {}", av_get_sample_fmt_name((AVSampleFormat)buffer->format)); } } } // namespace jami
4,702
C++
.cpp
118
34.271186
112
0.643968
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,784
dtmf.cpp
savoirfairelinux_jami-daemon/src/media/audio/sound/dtmf.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "dtmf.h" namespace jami { DTMF::DTMF(unsigned int sampleRate, AVSampleFormat sampleFormat) : currentTone_(0) , newTone_(0) , dtmfgenerator_(sampleRate, sampleFormat) {} void DTMF::startTone(char code) { newTone_ = code; } bool DTMF::generateDTMF(AVFrame* buffer) { try { if (currentTone_ != 0) { // Currently generating a DTMF tone if (currentTone_ == newTone_) { // Continue generating the same tone dtmfgenerator_.getNextSamples(buffer); return true; } else if (newTone_ != 0) { // New tone requested dtmfgenerator_.getSamples(buffer, newTone_); currentTone_ = newTone_; return true; } else { // Stop requested currentTone_ = newTone_; return false; } } else { // Not generating any DTMF tone if (newTone_) { // Requested to generate a DTMF tone dtmfgenerator_.getSamples(buffer, newTone_); currentTone_ = newTone_; return true; } else return false; } } catch (const DTMFException& e) { // invalid key return false; } } } // namespace jami
2,078
C++
.cpp
64
24.828125
73
0.601096
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,785
tonelist.cpp
savoirfairelinux_jami-daemon/src/media/audio/sound/tonelist.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * Inspired by tonegenerator of * Laurielle Lea <laurielle.lea@savoirfairelinux.com> (2004) * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "tonelist.h" #include <ciso646> // fix windows compiler bug namespace jami { TelephoneTone::CountryId TelephoneTone::getCountryId(const std::string& countryName) { if (countryName == "North America") return CountryId::ZID_NORTH_AMERICA; else if (countryName == "France") return CountryId::ZID_FRANCE; else if (countryName == "Australia") return CountryId::ZID_AUSTRALIA; else if (countryName == "United Kingdom") return CountryId::ZID_UNITED_KINGDOM; else if (countryName == "Spain") return CountryId::ZID_SPAIN; else if (countryName == "Italy") return CountryId::ZID_ITALY; else if (countryName == "Japan") return CountryId::ZID_JAPAN; else return CountryId::ZID_NORTH_AMERICA; // default } TelephoneTone::TelephoneTone(const std::string& countryName, unsigned int sampleRate, AVSampleFormat sampleFormat) : countryId_(getCountryId(countryName)) , currentTone_(Tone::ToneId::TONE_NULL) { buildTones(sampleRate, sampleFormat); } void TelephoneTone::setCurrentTone(Tone::ToneId toneId) { if (toneId != Tone::ToneId::TONE_NULL && currentTone_ != toneId) tones_[(size_t) toneId]->reset(); currentTone_ = toneId; } void TelephoneTone::setSampleRate(unsigned int sampleRate, AVSampleFormat sampleFormat) { buildTones(sampleRate, sampleFormat); } std::shared_ptr<Tone> TelephoneTone::getCurrentTone() { if (currentTone_ < Tone::ToneId::DIALTONE or currentTone_ >= Tone::ToneId::TONE_NULL) return nullptr; return tones_[(size_t) currentTone_]; } void TelephoneTone::buildTones(unsigned int sampleRate, AVSampleFormat sampleFormat) { const char* toneZone[(size_t) TelephoneTone::CountryId::ZID_COUNTRIES] [(size_t) Tone::ToneId::TONE_NULL] = {{ // ZID_NORTH_AMERICA "350+440", // Tone::TONE_DIALTONE "480+620/500,0/500", // Tone::TONE_BUSY "440+480/2000,0/4000", // Tone::TONE_RINGTONE "480+620/250,0/250", // Tone::TONE_CONGESTION }, { // ZID_FRANCE "440", "440/500,0/500", "440/1500,0/3500", "440/250,0/250", }, { // ZID_AUSTRALIA "413+438", "425/375,0/375", "413+438/400,0/200,413+438/400,0/2000", "425/375,0/375,420/375,8/375", }, { // ZID_UNITED_KINGDOM "350+440", "400/375,0/375", "400+450/400,0/200,400+450/400,0/2000", "400/400,0/350,400/225,0/525", }, { // ZID_SPAIN "425", "425/200,0/200", "425/1500,0/3000", "425/200,0/200,425/200,0/200,425/200,0/600", }, { // ZID_ITALY "425/600,0/1000,425/200,0/200", "425/500,0/500", "425/1000,0/4000", "425/200,0/200", }, { // ZID_JAPAN "400", "400/500,0/500", "400+15/1000,0/2000", "400/500,0/500", }}; tones_[(size_t) Tone::ToneId::DIALTONE] = std::make_shared<Tone>(toneZone[(size_t) countryId_][(size_t) Tone::ToneId::DIALTONE], sampleRate, sampleFormat); tones_[(size_t) Tone::ToneId::BUSY] = std::make_shared<Tone>(toneZone[(size_t) countryId_][(size_t) Tone::ToneId::BUSY], sampleRate, sampleFormat); tones_[(size_t) Tone::ToneId::RINGTONE] = std::make_shared<Tone>(toneZone[(size_t) countryId_][(size_t) Tone::ToneId::RINGTONE], sampleRate, sampleFormat); tones_[(size_t) Tone::ToneId::CONGESTION] = std::make_shared<Tone>(toneZone[(size_t) countryId_][(size_t) Tone::ToneId::CONGESTION], sampleRate, sampleFormat); } } // namespace jami
4,966
C++
.cpp
135
27.955556
114
0.580498
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,786
audiodevice.cpp
savoirfairelinux_jami-daemon/src/media/audio/coreaudio/osx/audiodevice.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "audiodevice.h" #if !TARGET_OS_IPHONE namespace jami { AudioDevice::AudioDevice(AudioDeviceID devid, bool isInput) { init(devid, isInput); } void AudioDevice::init(AudioDeviceID devid, bool isInput) { id_ = devid; isInput_ = isInput; if (id_ == kAudioDeviceUnknown) return; name_ = getName(); channels_ = countChannels(); UInt32 propsize = sizeof(Float32); AudioObjectPropertyScope theScope = isInput_ ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress theAddress = {kAudioDevicePropertySafetyOffset, theScope, 0}; // channel __Verify_noErr(AudioObjectGetPropertyData(id_, &theAddress, 0, NULL, &propsize, &safetyOffset_)); propsize = sizeof(UInt32); theAddress.mSelector = kAudioDevicePropertyBufferFrameSize; __Verify_noErr( AudioObjectGetPropertyData(id_, &theAddress, 0, NULL, &propsize, &bufferSizeFrames_)); propsize = sizeof(AudioStreamBasicDescription); theAddress.mSelector = kAudioDevicePropertyStreamFormat; __Verify_noErr(AudioObjectGetPropertyData(id_, &theAddress, 0, NULL, &propsize, &format_)); } bool AudioDevice::valid() const { return id_ != kAudioDeviceUnknown; } void AudioDevice::setBufferSize(UInt32 size) { UInt32 propsize = sizeof(UInt32); AudioObjectPropertyScope theScope = isInput_ ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress theAddress = {kAudioDevicePropertyBufferFrameSize, theScope, 0}; // channel __Verify_noErr(AudioObjectSetPropertyData(id_, &theAddress, 0, NULL, propsize, &size)); __Verify_noErr( AudioObjectGetPropertyData(id_, &theAddress, 0, NULL, &propsize, &bufferSizeFrames_)); } int AudioDevice::countChannels() const { OSStatus err; UInt32 propSize; int result = 0; AudioObjectPropertyScope theScope = isInput_ ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress theAddress = {kAudioDevicePropertyStreamConfiguration, theScope, 0}; // channel err = AudioObjectGetPropertyDataSize(id_, &theAddress, 0, NULL, &propSize); if (err) return 0; AudioBufferList* buflist = (AudioBufferList*) malloc(propSize); err = AudioObjectGetPropertyData(id_, &theAddress, 0, NULL, &propSize, buflist); if (!err) { for (UInt32 i = 0; i < buflist->mNumberBuffers; ++i) { result += buflist->mBuffers[i].mNumberChannels; } } free(buflist); return result; } std::string AudioDevice::getName() const { char buf[256]; UInt32 maxlen = sizeof(buf) - 1; AudioObjectPropertyScope theScope = isInput_ ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress theAddress = {kAudioDevicePropertyDeviceName, theScope, 0}; // channel __Verify_noErr(AudioObjectGetPropertyData(id_, &theAddress, 0, NULL, &maxlen, buf)); return buf; } } // namespace jami #endif // TARGET_OS_IPHONE
4,212
C++
.cpp
102
33.078431
101
0.662417
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,787
portaudiolayer.cpp
savoirfairelinux_jami-daemon/src/media/audio/portaudio/portaudiolayer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "portaudiolayer.h" #include "manager.h" #include "noncopyable.h" #include "audio/resampler.h" #include "audio/ringbufferpool.h" #include "audio/ringbuffer.h" #include "audio/audioloop.h" #include <portaudio.h> #include <algorithm> #include <cmath> namespace jami { enum Direction { Input = 0, Output = 1, IO = 2, End = 3 }; struct PortAudioLayer::PortAudioLayerImpl { PortAudioLayerImpl(PortAudioLayer&, const AudioPreference&); ~PortAudioLayerImpl(); void init(PortAudioLayer&); void initInput(PortAudioLayer&); void initOutput(PortAudioLayer&); void terminate() const; bool initInputStream(PortAudioLayer&); bool initOutputStream(PortAudioLayer&); bool initFullDuplexStream(PortAudioLayer&); bool apiInitialised_ {false}; std::vector<std::string> getDevicesByType(AudioDeviceType type) const; int getIndexByType(AudioDeviceType type); std::string getDeviceNameByType(const int index, AudioDeviceType type); PaDeviceIndex getApiIndexByType(AudioDeviceType type); std::string getApiDefaultDeviceName(AudioDeviceType type, bool commDevice) const; std::string deviceRecord_ {}; std::string devicePlayback_ {}; std::string deviceRingtone_ {}; static constexpr const int defaultIndex_ {0}; bool inputInitialized_ {false}; bool outputInitialized_ {false}; std::array<PaStream*, static_cast<int>(Direction::End)> streams_; int paOutputCallback(PortAudioLayer& parent, const int16_t* inputBuffer, int16_t* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); int paInputCallback(PortAudioLayer& parent, const int16_t* inputBuffer, int16_t* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); int paIOCallback(PortAudioLayer& parent, const int16_t* inputBuffer, int16_t* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); }; //################################################################################################## PortAudioLayer::PortAudioLayer(const AudioPreference& pref) : AudioLayer {pref} , pimpl_ {new PortAudioLayerImpl(*this, pref)} { setHasNativeAEC(false); setHasNativeNS(false); auto numDevices = Pa_GetDeviceCount(); if (numDevices < 0) { JAMI_ERR("Pa_CountDevices returned 0x%x", numDevices); return; } const PaDeviceInfo* deviceInfo; for (auto i = 0; i < numDevices; i++) { deviceInfo = Pa_GetDeviceInfo(i); JAMI_DBG("PortAudio device: %d, %s", i, deviceInfo->name); } } PortAudioLayer::~PortAudioLayer() { stopStream(); } std::vector<std::string> PortAudioLayer::getCaptureDeviceList() const { return pimpl_->getDevicesByType(AudioDeviceType::CAPTURE); } std::vector<std::string> PortAudioLayer::getPlaybackDeviceList() const { return pimpl_->getDevicesByType(AudioDeviceType::PLAYBACK); } int PortAudioLayer::getAudioDeviceIndex(const std::string& name, AudioDeviceType type) const { auto devices = pimpl_->getDevicesByType(type); auto it = std::find_if(devices.cbegin(), devices.cend(), [&name](const auto& deviceName) { return deviceName == name; }); return it != devices.end() ? std::distance(devices.cbegin(), it) : -1; } std::string PortAudioLayer::getAudioDeviceName(int index, AudioDeviceType type) const { (void) index; (void) type; return {}; } int PortAudioLayer::getIndexCapture() const { return pimpl_->getIndexByType(AudioDeviceType::CAPTURE); } int PortAudioLayer::getIndexPlayback() const { auto index = pimpl_->getIndexByType(AudioDeviceType::PLAYBACK); return index; } int PortAudioLayer::getIndexRingtone() const { return pimpl_->getIndexByType(AudioDeviceType::RINGTONE); } void PortAudioLayer::startStream(AudioDeviceType stream) { if (!pimpl_->apiInitialised_) { JAMI_WARN("PortAudioLayer API not initialised"); return; } auto startPlayback = [this](bool fullDuplexMode = false) -> bool { std::unique_lock lock(mutex_); if (status_.load() != Status::Idle) return false; bool ret {false}; if (fullDuplexMode) ret = pimpl_->initFullDuplexStream(*this); else ret = pimpl_->initOutputStream(*this); if (ret) { status_.store(Status::Started); lock.unlock(); flushUrgent(); flushMain(); } return ret; }; switch (stream) { case AudioDeviceType::ALL: if (!startPlayback(true)) { pimpl_->initInputStream(*this); startPlayback(); } break; case AudioDeviceType::CAPTURE: pimpl_->initInputStream(*this); break; case AudioDeviceType::PLAYBACK: case AudioDeviceType::RINGTONE: startPlayback(); break; } } void PortAudioLayer::stopStream(AudioDeviceType stream) { auto stopPaStream = [](PaStream* stream) -> bool { if (!stream || Pa_IsStreamStopped(stream) != paNoError) return false; auto err = Pa_StopStream(stream); if (err != paNoError) { JAMI_ERR("Pa_StopStream error: %s", Pa_GetErrorText(err)); return false; } err = Pa_CloseStream(stream); if (err != paNoError) { JAMI_ERR("Pa_CloseStream error: %s", Pa_GetErrorText(err)); return false; } return true; }; auto stopPlayback = [this, &stopPaStream](bool fullDuplexMode = false) -> bool { std::lock_guard lock(mutex_); if (status_.load() != Status::Started) return false; bool stopped = false; if (fullDuplexMode) stopped = stopPaStream(pimpl_->streams_[Direction::IO]); else stopped = stopPaStream(pimpl_->streams_[Direction::Output]); if (stopped) status_.store(Status::Idle); return stopped; }; bool stopped = false; switch (stream) { case AudioDeviceType::ALL: if (pimpl_->streams_[Direction::IO]) { stopped = stopPlayback(true); } else { stopped = stopPaStream(pimpl_->streams_[Direction::Input]) && stopPlayback(); } if (stopped) { recordChanged(false); playbackChanged(false); JAMI_DBG("PortAudioLayer I/O streams stopped"); } else return; break; case AudioDeviceType::CAPTURE: if (stopPaStream(pimpl_->streams_[Direction::Input])) { recordChanged(false); JAMI_DBG("PortAudioLayer input stream stopped"); } else return; break; case AudioDeviceType::PLAYBACK: case AudioDeviceType::RINGTONE: if (stopPlayback()) { playbackChanged(false); JAMI_DBG("PortAudioLayer output stream stopped"); } else return; break; } // Flush the ring buffers flushUrgent(); flushMain(); } void PortAudioLayer::updatePreference(AudioPreference& preference, int index, AudioDeviceType type) { auto deviceName = pimpl_->getDeviceNameByType(index, type); switch (type) { case AudioDeviceType::PLAYBACK: preference.setPortAudioDevicePlayback(deviceName); break; case AudioDeviceType::CAPTURE: preference.setPortAudioDeviceRecord(deviceName); break; case AudioDeviceType::RINGTONE: preference.setPortAudioDeviceRingtone(deviceName); break; default: break; } } //################################################################################################## PortAudioLayer::PortAudioLayerImpl::PortAudioLayerImpl(PortAudioLayer& parent, const AudioPreference& pref) : deviceRecord_ {pref.getPortAudioDeviceRecord()} , devicePlayback_ {pref.getPortAudioDevicePlayback()} , deviceRingtone_ {pref.getPortAudioDeviceRingtone()} { init(parent); } PortAudioLayer::PortAudioLayerImpl::~PortAudioLayerImpl() { terminate(); } void PortAudioLayer::PortAudioLayerImpl::initInput(PortAudioLayer& parent) { // convert out preference to an api index auto apiIndex = getApiIndexByType(AudioDeviceType::CAPTURE); // Pa_GetDefault[Comm]InputDevice returned paNoDevice or we already initialized the device if (apiIndex == paNoDevice || inputInitialized_) return; const auto inputDeviceInfo = Pa_GetDeviceInfo(apiIndex); if (!inputDeviceInfo) { // this represents complete failure after attempting a fallback to default JAMI_WARN("PortAudioLayer was unable to initialize input"); deviceRecord_.clear(); inputInitialized_ = true; return; } // if the device index is somehow no longer a device of the correct type, reset the // internal index to paNoDevice and reenter in an attempt to set the default // communications device if (inputDeviceInfo->maxInputChannels <= 0) { JAMI_WARN("PortAudioLayer was unable to initialize input, falling back to default device"); deviceRecord_.clear(); return initInput(parent); } // at this point, the device is of the correct type and can be opened parent.audioInputFormat_.sample_rate = inputDeviceInfo->defaultSampleRate; parent.audioInputFormat_.nb_channels = inputDeviceInfo->maxInputChannels; parent.hardwareInputFormatAvailable(parent.audioInputFormat_); JAMI_DBG("PortAudioLayer initialized input: %s {%d Hz, %d channels}", inputDeviceInfo->name, parent.audioInputFormat_.sample_rate, parent.audioInputFormat_.nb_channels); inputInitialized_ = true; } void PortAudioLayer::PortAudioLayerImpl::initOutput(PortAudioLayer& parent) { // convert out preference to an api index auto apiIndex = getApiIndexByType(AudioDeviceType::PLAYBACK); // Pa_GetDefault[Comm]OutputDevice returned paNoDevice or we already initialized the device if (apiIndex == paNoDevice || outputInitialized_) return; const auto outputDeviceInfo = Pa_GetDeviceInfo(apiIndex); if (!outputDeviceInfo) { // this represents complete failure after attempting a fallback to default JAMI_WARN("PortAudioLayer was unable to initialize output"); devicePlayback_.clear(); outputInitialized_ = true; return; } // if the device index is somehow no longer a device of the correct type, reset the // internal index to paNoDevice and reenter in an attempt to set the default // communications device if (outputDeviceInfo->maxOutputChannels <= 0) { JAMI_WARN("PortAudioLayer was unable to initialize output, falling back to default device"); devicePlayback_.clear(); return initOutput(parent); } // at this point, the device is of the correct type and can be opened parent.audioFormat_.sample_rate = outputDeviceInfo->defaultSampleRate; parent.audioFormat_.nb_channels = outputDeviceInfo->maxOutputChannels; parent.hardwareFormatAvailable(parent.audioFormat_); JAMI_DBG("PortAudioLayer initialized output: %s {%d Hz, %d channels}", outputDeviceInfo->name, parent.audioFormat_.sample_rate, parent.audioFormat_.nb_channels); outputInitialized_ = true; } void PortAudioLayer::PortAudioLayerImpl::init(PortAudioLayer& parent) { JAMI_DBG("PortAudioLayer Init"); const auto err = Pa_Initialize(); auto apiIndex = Pa_GetDefaultHostApi(); auto apiInfo = Pa_GetHostApiInfo(apiIndex); if (err != paNoError || apiInfo == nullptr) { JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); terminate(); return; } apiInitialised_ = true; JAMI_DBG() << "Portaudio initialized using: " << apiInfo->name; initInput(parent); initOutput(parent); std::fill(std::begin(streams_), std::end(streams_), nullptr); } std::vector<std::string> PortAudioLayer::PortAudioLayerImpl::getDevicesByType(AudioDeviceType type) const { std::vector<std::string> devices; auto numDevices = Pa_GetDeviceCount(); if (numDevices < 0) JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(numDevices)); else { for (int i = 0; i < numDevices; i++) { const auto deviceInfo = Pa_GetDeviceInfo(i); if (type == AudioDeviceType::CAPTURE) { if (deviceInfo->maxInputChannels > 0) devices.push_back(deviceInfo->name); } else if (deviceInfo->maxOutputChannels > 0) devices.push_back(deviceInfo->name); } // add the default device aliases if requested and if there are any devices of this type if (!devices.empty()) { // default comm (index:0) auto defaultDeviceName = getApiDefaultDeviceName(type, true); devices.insert(devices.begin(), "{{Default}} - " + defaultDeviceName); } } return devices; } int PortAudioLayer::PortAudioLayerImpl::getIndexByType(AudioDeviceType type) { auto devices = getDevicesByType(type); if (!devices.size()) { return 0; } std::string_view toMatch = (type == AudioDeviceType::CAPTURE ? deviceRecord_ : (type == AudioDeviceType::PLAYBACK ? devicePlayback_ : deviceRingtone_)); auto it = std::find_if(devices.cbegin(), devices.cend(), [&toMatch](const auto& deviceName) { return deviceName == toMatch; }); return it != devices.end() ? std::distance(devices.cbegin(), it) : 0; } std::string PortAudioLayer::PortAudioLayerImpl::getDeviceNameByType(const int index, AudioDeviceType type) { if (index == defaultIndex_) return {}; auto devices = getDevicesByType(type); if (!devices.size() || index >= devices.size()) return {}; return devices.at(index); } PaDeviceIndex PortAudioLayer::PortAudioLayerImpl::getApiIndexByType(AudioDeviceType type) { auto numDevices = Pa_GetDeviceCount(); if (numDevices < 0) JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(numDevices)); else { std::string_view toMatch = (type == AudioDeviceType::CAPTURE ? deviceRecord_ : (type == AudioDeviceType::PLAYBACK ? devicePlayback_ : deviceRingtone_)); if (toMatch.empty()) return type == AudioDeviceType::CAPTURE ? Pa_GetDefaultCommInputDevice() : Pa_GetDefaultCommOutputDevice(); for (int i = 0; i < numDevices; ++i) { if (const auto deviceInfo = Pa_GetDeviceInfo(i)) { if (deviceInfo->name == toMatch) return i; } } } return paNoDevice; } std::string PortAudioLayer::PortAudioLayerImpl::getApiDefaultDeviceName(AudioDeviceType type, bool commDevice) const { std::string deviceName {}; PaDeviceIndex deviceIndex {paNoDevice}; if (type == AudioDeviceType::CAPTURE) { deviceIndex = commDevice ? Pa_GetDefaultCommInputDevice() : Pa_GetDefaultInputDevice(); } else { deviceIndex = commDevice ? Pa_GetDefaultCommOutputDevice() : Pa_GetDefaultOutputDevice(); } if (const auto deviceInfo = Pa_GetDeviceInfo(deviceIndex)) { deviceName = deviceInfo->name; } return deviceName; } void PortAudioLayer::PortAudioLayerImpl::terminate() const { JAMI_DBG("PortAudioLayer terminate."); auto err = Pa_Terminate(); if (err != paNoError) JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); } static void openStreamDevice(PaStream** stream, PaDeviceIndex device, Direction direction, PaStreamCallback* callback, void* user_data) { auto is_out = direction == Direction::Output; auto device_info = Pa_GetDeviceInfo(device); PaStreamParameters params; params.device = device; params.channelCount = is_out ? device_info->maxOutputChannels : device_info->maxInputChannels; params.sampleFormat = paInt16; params.suggestedLatency = is_out ? device_info->defaultLowOutputLatency : device_info->defaultLowInputLatency; params.hostApiSpecificStreamInfo = nullptr; auto err = Pa_OpenStream(stream, is_out ? nullptr : &params, is_out ? &params : nullptr, device_info->defaultSampleRate, paFramesPerBufferUnspecified, paNoFlag, callback, user_data); if (err != paNoError) JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); } static void openFullDuplexStream(PaStream** stream, PaDeviceIndex inputDeviceIndex, PaDeviceIndex ouputDeviceIndex, PaStreamCallback* callback, void* user_data) { auto input_device_info = Pa_GetDeviceInfo(inputDeviceIndex); auto output_device_info = Pa_GetDeviceInfo(ouputDeviceIndex); PaStreamParameters inputParams; inputParams.device = inputDeviceIndex; inputParams.channelCount = input_device_info->maxInputChannels; inputParams.sampleFormat = paInt16; inputParams.suggestedLatency = input_device_info->defaultLowInputLatency; inputParams.hostApiSpecificStreamInfo = nullptr; PaStreamParameters outputParams; outputParams.device = ouputDeviceIndex; outputParams.channelCount = output_device_info->maxOutputChannels; outputParams.sampleFormat = paInt16; outputParams.suggestedLatency = output_device_info->defaultLowOutputLatency; outputParams.hostApiSpecificStreamInfo = nullptr; auto err = Pa_OpenStream(stream, &inputParams, &outputParams, std::min(input_device_info->defaultSampleRate, input_device_info->defaultSampleRate), paFramesPerBufferUnspecified, paNoFlag, callback, user_data); if (err != paNoError) JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); } bool PortAudioLayer::PortAudioLayerImpl::initInputStream(PortAudioLayer& parent) { JAMI_DBG("Open PortAudio Input Stream"); auto& stream = streams_[Direction::Input]; auto apiIndex = getApiIndexByType(AudioDeviceType::CAPTURE); if (apiIndex != paNoDevice) { openStreamDevice( &streams_[Direction::Input], apiIndex, Direction::Input, [](const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) -> int { auto layer = static_cast<PortAudioLayer*>(userData); return layer->pimpl_->paInputCallback(*layer, static_cast<const int16_t*>(inputBuffer), static_cast<int16_t*>(outputBuffer), framesPerBuffer, timeInfo, statusFlags); }, &parent); } else { JAMI_ERR("Error: No valid input device. There will be no mic."); return false; } JAMI_DBG("Starting PortAudio Input Stream"); auto err = Pa_StartStream(stream); if (err != paNoError) { JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); return false; } parent.recordChanged(true); return true; } bool PortAudioLayer::PortAudioLayerImpl::initOutputStream(PortAudioLayer& parent) { JAMI_DBG("Open PortAudio Output Stream"); auto& stream = streams_[Direction::Output]; auto apiIndex = getApiIndexByType(AudioDeviceType::PLAYBACK); if (apiIndex != paNoDevice) { openStreamDevice( &stream, apiIndex, Direction::Output, [](const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) -> int { auto layer = static_cast<PortAudioLayer*>(userData); return layer->pimpl_->paOutputCallback(*layer, static_cast<const int16_t*>(inputBuffer), static_cast<int16_t*>(outputBuffer), framesPerBuffer, timeInfo, statusFlags); }, &parent); } else { JAMI_ERR("Error: No valid output device. There will be no sound."); return false; } JAMI_DBG("Starting PortAudio Output Stream"); auto err = Pa_StartStream(stream); if (err != paNoError) { JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); return false; } parent.playbackChanged(true); return true; } bool PortAudioLayer::PortAudioLayerImpl::initFullDuplexStream(PortAudioLayer& parent) { auto apiIndexRecord = getApiIndexByType(AudioDeviceType::CAPTURE); auto apiIndexPlayback = getApiIndexByType(AudioDeviceType::PLAYBACK); if (apiIndexRecord == paNoDevice || apiIndexPlayback == paNoDevice) { JAMI_ERR("Error: Invalid input/output devices. There will be no audio."); return false; } JAMI_DBG("Open PortAudio Full-duplex input/output stream"); auto& stream = streams_[Direction::IO]; openFullDuplexStream( &stream, apiIndexRecord, apiIndexPlayback, [](const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) -> int { auto layer = static_cast<PortAudioLayer*>(userData); return layer->pimpl_->paIOCallback(*layer, static_cast<const int16_t*>(inputBuffer), static_cast<int16_t*>(outputBuffer), framesPerBuffer, timeInfo, statusFlags); }, &parent); JAMI_DBG("Start PortAudio I/O Streams"); auto err = Pa_StartStream(stream); if (err != paNoError) { JAMI_ERR("PortAudioLayer error: %s", Pa_GetErrorText(err)); return false; } parent.recordChanged(true); parent.playbackChanged(true); return true; } int PortAudioLayer::PortAudioLayerImpl::paOutputCallback(PortAudioLayer& parent, const int16_t* inputBuffer, int16_t* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { // unused arguments (void) inputBuffer; (void) timeInfo; (void) statusFlags; auto toPlay = parent.getPlayback(parent.audioFormat_, framesPerBuffer); if (!toPlay) { std::fill_n(outputBuffer, framesPerBuffer * parent.audioFormat_.nb_channels, 0); return paContinue; } auto nFrames = toPlay->pointer()->nb_samples * toPlay->pointer()->ch_layout.nb_channels; std::copy_n((int16_t*) toPlay->pointer()->extended_data[0], nFrames, outputBuffer); return paContinue; } int PortAudioLayer::PortAudioLayerImpl::paInputCallback(PortAudioLayer& parent, const int16_t* inputBuffer, int16_t* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { // unused arguments (void) outputBuffer; (void) timeInfo; (void) statusFlags; if (framesPerBuffer == 0) { JAMI_WARN("No frames for input."); return paContinue; } auto inBuff = std::make_shared<AudioFrame>(parent.audioInputFormat_, framesPerBuffer); auto nFrames = framesPerBuffer * parent.audioInputFormat_.nb_channels; if (parent.isCaptureMuted_) libav_utils::fillWithSilence(inBuff->pointer()); else std::copy_n(inputBuffer, nFrames, (int16_t*) inBuff->pointer()->extended_data[0]); parent.putRecorded(std::move(inBuff)); return paContinue; } int PortAudioLayer::PortAudioLayerImpl::paIOCallback(PortAudioLayer& parent, const int16_t* inputBuffer, int16_t* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { paInputCallback(parent, inputBuffer, nullptr, framesPerBuffer, timeInfo, statusFlags); paOutputCallback(parent, nullptr, outputBuffer, framesPerBuffer, timeInfo, statusFlags); return paContinue; } } // namespace jami
27,646
C++
.cpp
693
29.974026
100
0.61363
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,788
webrtc.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/webrtc.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "webrtc.h" #include "logger.h" #include <webrtc/modules/audio_processing/include/audio_processing.h> namespace jami { inline size_t webrtcFrameSize(AudioFormat format) { return (size_t) (webrtc::AudioProcessing::kChunkSizeMs * format.sample_rate / 1000); } constexpr int webrtcNoError = webrtc::AudioProcessing::kNoError; WebRTCAudioProcessor::WebRTCAudioProcessor(AudioFormat format, unsigned /* frameSize */) : AudioProcessor(format.withSampleFormat(AV_SAMPLE_FMT_FLTP), webrtcFrameSize(format)) { JAMI_LOG("[webrtc-ap] WebRTCAudioProcessor, frame size = {:d} (={:d} ms), channels = {:d}", frameSize_, frameDurationMs_, format_.nb_channels); webrtc::Config config; config.Set<webrtc::ExtendedFilter>(new webrtc::ExtendedFilter(true)); config.Set<webrtc::DelayAgnostic>(new webrtc::DelayAgnostic(true)); apm.reset(webrtc::AudioProcessing::Create(config)); webrtc::StreamConfig streamConfig((int) format_.sample_rate, (int) format_.nb_channels); webrtc::ProcessingConfig pconfig = { streamConfig, /* input stream */ streamConfig, /* output stream */ streamConfig, /* reverse input stream */ streamConfig, /* reverse output stream */ }; if (apm->Initialize(pconfig) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error initialising audio processing module"); } } void WebRTCAudioProcessor::enableNoiseSuppression(bool enabled) { JAMI_LOG("[webrtc-ap] enableNoiseSuppression {}", enabled); if (apm->noise_suppression()->Enable(enabled) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error enabling noise suppression"); } if (apm->noise_suppression()->set_level(webrtc::NoiseSuppression::kVeryHigh) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error setting noise suppression level"); } if (apm->high_pass_filter()->Enable(enabled) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error enabling high pass filter"); } } void WebRTCAudioProcessor::enableAutomaticGainControl(bool enabled) { JAMI_LOG("[webrtc-ap] enableAutomaticGainControl {}", enabled); if (apm->gain_control()->Enable(enabled) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error enabling automatic gain control"); } if (apm->gain_control()->set_analog_level_limits(0, 255) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error setting automatic gain control analog level limits"); } if (apm->gain_control()->set_mode(webrtc::GainControl::kAdaptiveAnalog) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error setting automatic gain control mode"); } } void WebRTCAudioProcessor::enableEchoCancel(bool enabled) { JAMI_LOG("[webrtc-ap] enableEchoCancel {}", enabled); if (apm->echo_cancellation()->Enable(enabled) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error enabling echo cancellation"); } if (apm->echo_cancellation()->set_suppression_level( webrtc::EchoCancellation::SuppressionLevel::kHighSuppression) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error setting echo cancellation level"); } if (apm->echo_cancellation()->enable_drift_compensation(true) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error enabling echo cancellation drift compensation"); } } void WebRTCAudioProcessor::enableVoiceActivityDetection(bool enabled) { JAMI_LOG("[webrtc-ap] enableVoiceActivityDetection {}", enabled); if (apm->voice_detection()->Enable(enabled) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error enabling voice activation detection"); } if (apm->voice_detection()->set_likelihood(webrtc::VoiceDetection::kVeryLowLikelihood) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error setting voice detection likelihood"); } // asserted to be 10 in voice_detection_impl.cc if (apm->voice_detection()->set_frame_size_ms(10) != webrtcNoError) { JAMI_ERROR("[webrtc-ap] Error setting voice detection frame size"); } } std::shared_ptr<AudioFrame> WebRTCAudioProcessor::getProcessed() { if (tidyQueues()) { return {}; } int driftSamples = playbackQueue_.samples() - recordQueue_.samples(); auto playback = playbackQueue_.dequeue(); auto record = recordQueue_.dequeue(); if (!playback || !record) { return {}; } webrtc::StreamConfig sc((int) format_.sample_rate, (int) format_.nb_channels); // process reverse in place float** playData = (float**) playback->pointer()->extended_data; if (apm->ProcessReverseStream(playData, sc, sc, playData) != webrtcNoError) { JAMI_ERR("[webrtc-ap] ProcessReverseStream failed"); } // process deinterleaved float recorded data // TODO: maybe implement this to see if it's better than automatic drift compensation // (it MUST be called prior to ProcessStream) // delay = (t_render - t_analyze) + (t_process - t_capture) if (apm->set_stream_delay_ms(0) != webrtcNoError) { JAMI_ERR("[webrtc-ap] set_stream_delay_ms failed"); } if (apm->gain_control()->set_stream_analog_level(analogLevel_) != webrtcNoError) { JAMI_ERR("[webrtc-ap] set_stream_analog_level failed"); } apm->echo_cancellation()->set_stream_drift_samples(driftSamples); // process in place float** recData = (float**) record->pointer()->extended_data; if (apm->ProcessStream(recData, sc, sc, recData) != webrtcNoError) { JAMI_ERR("[webrtc-ap] ProcessStream failed"); } analogLevel_ = apm->gain_control()->stream_analog_level(); record->has_voice = apm->voice_detection()->is_enabled() && getStabilizedVoiceActivity(apm->voice_detection()->stream_has_voice()); return record; } } // namespace jami
6,691
C++
.cpp
148
39.054054
102
0.680006
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,789
null_audio_processor.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/null_audio_processor.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "null_audio_processor.h" #include <cassert> namespace jami { NullAudioProcessor::NullAudioProcessor(AudioFormat format, unsigned frameSize) : AudioProcessor(format, frameSize) { JAMI_DBG("[null_audio] NullAudioProcessor, frame size = %d (=%d ms), channels = %d", frameSize, frameDurationMs_, format.nb_channels); } std::shared_ptr<AudioFrame> NullAudioProcessor::getProcessed() { if (tidyQueues()) { return {}; } playbackQueue_.dequeue(); return recordQueue_.dequeue(); }; } // namespace jami
1,341
C++
.cpp
37
31.540541
89
0.696899
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,790
speex.cpp
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/speex.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "speex.h" #include "audio/audiolayer.h" #ifndef _MSC_VER #if __has_include(<speex/speexdsp_config_types.h>) #include <speex/speexdsp_config_types.h> #else #include <speex/speex_config_types.h> #endif #endif extern "C" { #include <speex/speex_echo.h> #include <speex/speex_preprocess.h> } #include <cstdint> #include <memory> #include <vector> namespace jami { inline AudioFormat audioFormatToSampleFormat(AudioFormat format) { return {format.sample_rate, format.nb_channels, AV_SAMPLE_FMT_S16}; } SpeexAudioProcessor::SpeexAudioProcessor(AudioFormat format, unsigned frameSize) : AudioProcessor(format.withSampleFormat(AV_SAMPLE_FMT_S16), frameSize) , echoState(speex_echo_state_init_mc((int) frameSize, (int) frameSize * 16, (int) format_.nb_channels, (int) format_.nb_channels), &speex_echo_state_destroy) , procBuffer(std::make_unique<AudioFrame>(format.withSampleFormat(AV_SAMPLE_FMT_S16P), frameSize_)) { JAMI_DBG("[speex-dsp] SpeexAudioProcessor, frame size = %d (=%d ms), channels = %d", frameSize, frameDurationMs_, format_.nb_channels); // set up speex echo state speex_echo_ctl(echoState.get(), SPEEX_ECHO_SET_SAMPLING_RATE, &format_.sample_rate); // speex specific value to turn feature on (need to pass a pointer to it) spx_int32_t speexOn = 1; // probability integers, i.e. 50 means 50% // vad will be true if speex's raw probability calculation is higher than this in any case spx_int32_t probStart = 99; // vad will be true if voice was active last frame // AND speex's raw probability calculation is higher than this spx_int32_t probContinue = 90; // maximum noise suppression in dB (negative) spx_int32_t maxNoiseSuppress = -50; // set up speex preprocess states, one for each channel // note that they are not enabled here, but rather in the enable* functions for (unsigned int i = 0; i < format_.nb_channels; i++) { auto channelPreprocessorState = SpeexPreprocessStatePtr(speex_preprocess_state_init((int) frameSize, (int) format_.sample_rate), &speex_preprocess_state_destroy); // set max noise suppression level speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &maxNoiseSuppress); // set up voice activity values speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_VAD, &speexOn); speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_PROB_START, &probStart); speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_PROB_CONTINUE, &probContinue); // keep track of this channel's preprocessor state preprocessorStates.push_back(std::move(channelPreprocessorState)); } JAMI_INFO("[speex-dsp] Done initializing"); } void SpeexAudioProcessor::enableEchoCancel(bool enabled) { JAMI_DBG("[speex-dsp] enableEchoCancel %d", enabled); // need to set member variable so we know to do it in getProcessed shouldAEC = enabled; if (enabled) { // reset the echo canceller speex_echo_state_reset(echoState.get()); for (auto& channelPreprocessorState : preprocessorStates) { // attach our already-created echo canceller speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_ECHO_STATE, echoState.get()); } } else { for (auto& channelPreprocessorState : preprocessorStates) { // detach echo canceller (set it to NULL) // don't destroy it though, we will reset it when necessary speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_ECHO_STATE, NULL); } } } void SpeexAudioProcessor::enableNoiseSuppression(bool enabled) { JAMI_DBG("[speex-dsp] enableNoiseSuppression %d", enabled); spx_int32_t speexSetValue = (spx_int32_t) enabled; // for each preprocessor for (auto& channelPreprocessorState : preprocessorStates) { // set denoise status speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_DENOISE, &speexSetValue); // set de-reverb status speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_DEREVERB, &speexSetValue); } } void SpeexAudioProcessor::enableAutomaticGainControl(bool enabled) { JAMI_DBG("[speex-dsp] enableAutomaticGainControl %d", enabled); spx_int32_t speexSetValue = (spx_int32_t) enabled; // for each preprocessor for (auto& channelPreprocessorState : preprocessorStates) { // set AGC status speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_AGC, &speexSetValue); } } void SpeexAudioProcessor::enableVoiceActivityDetection(bool enabled) { JAMI_DBG("[speex-dsp] enableVoiceActivityDetection %d", enabled); shouldDetectVoice = enabled; spx_int32_t speexSetValue = (spx_int32_t) enabled; for (auto& channelPreprocessorState : preprocessorStates) { speex_preprocess_ctl(channelPreprocessorState.get(), SPEEX_PREPROCESS_SET_VAD, &speexSetValue); } } std::shared_ptr<AudioFrame> SpeexAudioProcessor::getProcessed() { if (tidyQueues()) { return {}; } auto playback = playbackQueue_.dequeue(); auto record = recordQueue_.dequeue(); if (!playback || !record) { return {}; } std::shared_ptr<AudioFrame> processed; if (shouldAEC) { // we want to echo cancel // multichannel, output into processed processed = std::make_shared<AudioFrame>(record->getFormat(), record->getFrameSize()); speex_echo_cancellation(echoState.get(), (int16_t*) record->pointer()->data[0], (int16_t*) playback->pointer()->data[0], (int16_t*) processed->pointer()->data[0]); } else { // don't want to echo cancel, so just use record frame instead processed = record; } deinterleaveResampler.resample(processed->pointer(), procBuffer->pointer()); // overall voice activity bool overallVad = false; // current channel voice activity int channelVad; // run preprocess on each channel int channel = 0; for (auto& channelPreprocessorState : preprocessorStates) { // preprocesses in place, returns voice activity boolean channelVad = speex_preprocess_run(channelPreprocessorState.get(), (int16_t*)procBuffer->pointer()->data[channel]); // boolean OR overallVad |= channelVad; channel += 1; } interleaveResampler.resample(procBuffer->pointer(), processed->pointer()); // add stabilized voice activity to the AudioFrame processed->has_voice = shouldDetectVoice && getStabilizedVoiceActivity(overallVad); return processed; } } // namespace jami
8,666
C++
.cpp
198
33.570707
123
0.624881
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,791
conversation.cpp
savoirfairelinux_jami-daemon/src/jamidht/conversation.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "conversation.h" #include "account_const.h" #include "fileutils.h" #include "jamiaccount.h" #include "client/ring_signal.h" #include <charconv> #include <json/json.h> #include <string_view> #include <opendht/thread_pool.h> #include <tuple> #include <optional> #include "swarm/swarm_manager.h" #ifdef ENABLE_PLUGIN #include "manager.h" #include "plugin/jamipluginmanager.h" #include "plugin/streamdata.h" #endif #include "jami/conversation_interface.h" namespace jami { static const char* const LAST_MODIFIED = "lastModified"; static const auto jsonBuilder = [] { Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return wbuilder; }(); ConvInfo::ConvInfo(const Json::Value& json) { id = json[ConversationMapKeys::ID].asString(); created = json[ConversationMapKeys::CREATED].asLargestUInt(); removed = json[ConversationMapKeys::REMOVED].asLargestUInt(); erased = json[ConversationMapKeys::ERASED].asLargestUInt(); for (const auto& v : json[ConversationMapKeys::MEMBERS]) { members.emplace(v["uri"].asString()); } lastDisplayed = json[ConversationMapKeys::LAST_DISPLAYED].asString(); } Json::Value ConvInfo::toJson() const { Json::Value json; json[ConversationMapKeys::ID] = id; json[ConversationMapKeys::CREATED] = Json::Int64(created); if (removed) { json[ConversationMapKeys::REMOVED] = Json::Int64(removed); } if (erased) { json[ConversationMapKeys::ERASED] = Json::Int64(erased); } for (const auto& m : members) { Json::Value member; member["uri"] = m; json[ConversationMapKeys::MEMBERS].append(member); } json[ConversationMapKeys::LAST_DISPLAYED] = lastDisplayed; return json; } // ConversationRequest ConversationRequest::ConversationRequest(const Json::Value& json) { received = json[ConversationMapKeys::RECEIVED].asLargestUInt(); declined = json[ConversationMapKeys::DECLINED].asLargestUInt(); from = json[ConversationMapKeys::FROM].asString(); conversationId = json[ConversationMapKeys::CONVERSATIONID].asString(); auto& md = json[ConversationMapKeys::METADATAS]; for (const auto& member : md.getMemberNames()) { metadatas.emplace(member, md[member].asString()); } } Json::Value ConversationRequest::toJson() const { Json::Value json; json[ConversationMapKeys::CONVERSATIONID] = conversationId; json[ConversationMapKeys::FROM] = from; json[ConversationMapKeys::RECEIVED] = static_cast<uint32_t>(received); if (declined) json[ConversationMapKeys::DECLINED] = static_cast<uint32_t>(declined); for (const auto& [key, value] : metadatas) { json[ConversationMapKeys::METADATAS][key] = value; } return json; } std::map<std::string, std::string> ConversationRequest::toMap() const { auto result = metadatas; result[ConversationMapKeys::ID] = conversationId; result[ConversationMapKeys::FROM] = from; if (declined) result[ConversationMapKeys::DECLINED] = std::to_string(declined); result[ConversationMapKeys::RECEIVED] = std::to_string(received); return result; } using MessageList = std::list<std::shared_ptr<libjami::SwarmMessage>>; struct History { MessageList messageList {}; std::map<std::string, std::shared_ptr<libjami::SwarmMessage>> quickAccess {}; std::map<std::string, std::list<std::shared_ptr<libjami::SwarmMessage>>> pendingEditions {}; std::map<std::string, std::list<std::map<std::string, std::string>>> pendingReactions {}; }; class Conversation::Impl { public: Impl(const std::shared_ptr<JamiAccount>& account, ConversationMode mode, const std::string& otherMember = "") : repository_(ConversationRepository::createConversation(account, mode, otherMember)) , account_(account) , accountId_(account->getAccountID()) , userId_(account->getUsername()) , deviceId_(account->currentDeviceId()) { if (!repository_) { throw std::logic_error("Unable to create repository"); } init(account); } Impl(const std::shared_ptr<JamiAccount>& account, const std::string& conversationId) : account_(account) , accountId_(account->getAccountID()) , userId_(account->getUsername()) , deviceId_(account->currentDeviceId()) { repository_ = std::make_unique<ConversationRepository>(account, conversationId); if (!repository_) { throw std::logic_error("Unable to create repository"); } init(account); } Impl(const std::shared_ptr<JamiAccount>& account, const std::string& remoteDevice, const std::string& conversationId) : account_(account) , accountId_(account->getAccountID()) , userId_(account->getUsername()) , deviceId_(account->currentDeviceId()) { std::vector<ConversationCommit> commits; repository_ = ConversationRepository::cloneConversation(account, remoteDevice, conversationId, [&](auto c) { commits = std::move(c); }); if (!repository_) { emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, conversationId, EFETCH, "Unable to clone repository"); throw std::logic_error("Unable to clone repository"); } // To detect current active calls, we need to check history conversationDataPath_ = fileutils::get_data_dir() / accountId_ / "conversation_data" / conversationId; activeCallsPath_ = conversationDataPath_ / ConversationMapKeys::ACTIVE_CALLS; initActiveCalls(repository_->convCommitsToMap(commits)); init(account); } void init(const std::shared_ptr<JamiAccount>& account) { ioContext_ = Manager::instance().ioContext(); fallbackTimer_ = std::make_unique<asio::steady_timer>(*ioContext_); swarmManager_ = std::make_shared<SwarmManager>(NodeId(deviceId_), Manager::instance().getSeededRandomEngine(), [account = account_](const DeviceId& deviceId) { if (auto acc = account.lock()) { return acc->isConnectedWith(deviceId); } return false; }); swarmManager_->setMobility(account->isMobile()); transferManager_ = std::make_shared<TransferManager>(accountId_, "", repository_->id(), Manager::instance().getSeededRandomEngine()); conversationDataPath_ = fileutils::get_data_dir() / accountId_ / "conversation_data" / repository_->id(); fetchedPath_ = conversationDataPath_ / "fetched"; statusPath_ = conversationDataPath_ / "status"; sendingPath_ = conversationDataPath_ / "sending"; preferencesPath_ = conversationDataPath_ / ConversationMapKeys::PREFERENCES; activeCallsPath_ = conversationDataPath_ / ConversationMapKeys::ACTIVE_CALLS; hostedCallsPath_ = conversationDataPath_ / ConversationMapKeys::HOSTED_CALLS; loadActiveCalls(); loadStatus(); typers_ = std::make_shared<Typers>(account, repository_->id()); } const std::string& toString() const { if (fmtStr_.empty()) { if (repository_->mode() == ConversationMode::ONE_TO_ONE) { auto peer = userId_; for (const auto& member : repository_->getInitialMembers()) { if (member != userId_) { peer = member; } } fmtStr_ = fmt::format("[Conversation (1:1) {}]", peer); } else { fmtStr_ = fmt::format("[Conversation {}]", repository_->id()); } } return fmtStr_; } mutable std::string fmtStr_; ~Impl() { try { if (fallbackTimer_) fallbackTimer_->cancel(); } catch (const std::exception& e) { JAMI_ERROR("[Conversation {:s}] {:s}", toString(), e.what()); } } /** * If, for whatever reason, the daemon is stopped while hosting a conference, * we need to announce the end of this call when restarting. * To avoid to keep active calls forever. */ std::vector<std::string> commitsEndedCalls(); bool isAdmin() const; std::filesystem::path repoPath() const; void announce(const std::string& commitId, bool commitFromSelf = false) const { std::vector<std::string> vec; if (!commitId.empty()) vec.emplace_back(commitId); announce(vec, commitFromSelf); } void announce(const std::vector<std::string>& commits, bool commitFromSelf = false) const { std::vector<ConversationCommit> convcommits; convcommits.reserve(commits.size()); for (const auto& cid : commits) { auto commit = repository_->getCommit(cid); if (commit != std::nullopt) { convcommits.emplace_back(*commit); } } announce(repository_->convCommitsToMap(convcommits), commitFromSelf); } /** * Initialize activeCalls_ from the list of commits in the repository * @param commits Commits in reverse chronological order (i.e. from newest to oldest) */ void initActiveCalls(const std::vector<std::map<std::string, std::string>>& commits) const { std::unordered_set<std::string> invalidHostUris; std::unordered_set<std::string> invalidCallIds; std::lock_guard lk(activeCallsMtx_); for (const auto& commit : commits) { if (commit.at("type") == "member") { // Each commit of type "member" has an "action" field whose value can be one // of the following: "add", "join", "remove", "ban", "unban" // In the case of "remove" and "ban", we need to add the member's URI to // invalidHostUris to ensure that any call they may have started in the past // is no longer considered active. // For the other actions, there's no harm in adding the member's URI anyway, // since it's not possible to start hosting a call before joining the swarm (or // before getting unbanned in the case of previously banned members). invalidHostUris.emplace(commit.at("uri")); } else if (commit.find("confId") != commit.end() && commit.find("uri") != commit.end() && commit.find("device") != commit.end()) { // The commit indicates either the end or the beginning of a call // (depending on whether there is a "duration" field or not). auto convId = repository_->id(); auto confId = commit.at("confId"); auto uri = commit.at("uri"); auto device = commit.at("device"); if (commit.find("duration") == commit.end() && invalidCallIds.find(confId) == invalidCallIds.end() && invalidHostUris.find(uri) == invalidHostUris.end()) { std::map<std::string, std::string> activeCall; activeCall["id"] = confId; activeCall["uri"] = uri; activeCall["device"] = device; activeCalls_.emplace_back(activeCall); fmt::print("swarm:{} new active call detected: {} (on device {}, account {})\n", convId, confId, device, uri); } // Even if the call was active, we still add its ID to invalidCallIds to make sure it // doesn't get added a second time. (This shouldn't happen normally, but in practice // there are sometimes multiple commits indicating the beginning of the same call.) invalidCallIds.emplace(confId); } } saveActiveCalls(); emitSignal<libjami::ConfigurationSignal::ActiveCallsChanged>(accountId_, repository_->id(), activeCalls_); } /** * Update activeCalls_ via announced commits (in load or via new commits) * @param commit Commit to check * @param eraseOnly If we want to ignore added commits * @param emitSig If we want to emit to client * @note eraseOnly is used by loadMessages. This is a fail-safe, this SHOULD NOT happen */ void updateActiveCalls(const std::map<std::string, std::string>& commit, bool eraseOnly = false, bool emitSig = true) const { if (!repository_) return; if (commit.at("type") == "member") { // In this case, we need to check if we are not removing a hosting member or device std::lock_guard lk(activeCallsMtx_); auto it = activeCalls_.begin(); auto updateActives = false; while (it != activeCalls_.end()) { if (it->at("uri") == commit.at("uri") || it->at("device") == commit.at("uri")) { JAMI_DEBUG("Removing {:s} from the active calls, because {:s} left", it->at("id"), commit.at("uri")); it = activeCalls_.erase(it); updateActives = true; } else { ++it; } } if (updateActives) { saveActiveCalls(); if (emitSig) emitSignal<libjami::ConfigurationSignal::ActiveCallsChanged>(accountId_, repository_->id(), activeCalls_); } return; } // Else, it's a call information if (commit.find("confId") != commit.end() && commit.find("uri") != commit.end() && commit.find("device") != commit.end()) { auto convId = repository_->id(); auto confId = commit.at("confId"); auto uri = commit.at("uri"); auto device = commit.at("device"); std::lock_guard lk(activeCallsMtx_); auto itActive = std::find_if(activeCalls_.begin(), activeCalls_.end(), [&](const auto& value) { return value.at("id") == confId && value.at("uri") == uri && value.at("device") == device; }); if (commit.find("duration") == commit.end()) { if (itActive == activeCalls_.end() && !eraseOnly) { JAMI_DEBUG( "swarm:{:s} new current call detected: {:s} on device {:s}, account {:s}", convId, confId, device, uri); std::map<std::string, std::string> activeCall; activeCall["id"] = confId; activeCall["uri"] = uri; activeCall["device"] = device; activeCalls_.emplace_back(activeCall); saveActiveCalls(); if (emitSig) emitSignal<libjami::ConfigurationSignal::ActiveCallsChanged>(accountId_, repository_ ->id(), activeCalls_); } } else { if (itActive != activeCalls_.end()) { itActive = activeCalls_.erase(itActive); // Unlikely, but we must ensure that no duplicate exists while (itActive != activeCalls_.end()) { itActive = std::find_if(itActive, activeCalls_.end(), [&](const auto& value) { return value.at("id") == confId && value.at("uri") == uri && value.at("device") == device; }); if (itActive != activeCalls_.end()) { JAMI_ERROR("Duplicate call found. (This is a bug)"); itActive = activeCalls_.erase(itActive); } } if (eraseOnly) { JAMI_WARNING("previous swarm:{:s} call finished detected: {:s} on device " "{:s}, account {:s}", convId, confId, device, uri); } else { JAMI_DEBUG("swarm:{:s} call finished: {:s} on device {:s}, account {:s}", convId, confId, device, uri); } } saveActiveCalls(); if (emitSig) emitSignal<libjami::ConfigurationSignal::ActiveCallsChanged>(accountId_, repository_->id(), activeCalls_); } } } void announce(const std::vector<std::map<std::string, std::string>>& commits, bool commitFromSelf = false) const { if (!repository_) return; auto convId = repository_->id(); auto ok = !commits.empty(); auto lastId = ok ? commits.rbegin()->at(ConversationMapKeys::ID) : ""; addToHistory(commits, true, commitFromSelf); if (ok) { bool announceMember = false; for (const auto& c : commits) { // Announce member events if (c.at("type") == "member") { if (c.find("uri") != c.end() && c.find("action") != c.end()) { const auto& uri = c.at("uri"); const auto& actionStr = c.at("action"); auto action = -1; if (actionStr == "add") action = 0; else if (actionStr == "join") action = 1; else if (actionStr == "remove") action = 2; else if (actionStr == "ban") action = 3; else if (actionStr == "unban") action = 4; if (actionStr == "ban" || actionStr == "remove") { // In this case, a potential host was removed during a call. updateActiveCalls(c); typers_->removeTyper(uri); } if (action != -1) { announceMember = true; emitSignal<libjami::ConversationSignal::ConversationMemberEvent>( accountId_, convId, uri, action); } } } else if (c.at("type") == "application/call-history+json") { updateActiveCalls(c); } #ifdef ENABLE_PLUGIN auto& pluginChatManager = Manager::instance().getJamiPluginManager().getChatServicesManager(); if (pluginChatManager.hasHandlers()) { auto cm = std::make_shared<JamiMessage>(accountId_, convId, c.at("author") != userId_, c, false); cm->isSwarm = true; pluginChatManager.publishMessage(std::move(cm)); } #endif // announce message emitSignal<libjami::ConversationSignal::MessageReceived>(accountId_, convId, c); } if (announceMember && onMembersChanged_) { onMembersChanged_(repository_->memberUris("", {})); } } } void loadStatus() { try { // read file auto file = fileutils::loadFile(statusPath_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::lock_guard lk {messageStatusMtx_}; oh.get().convert(messagesStatus_); } catch (const std::exception& e) { } } void saveStatus() { std::ofstream file(statusPath_, std::ios::trunc | std::ios::binary); msgpack::pack(file, messagesStatus_); } void loadActiveCalls() const { try { // read file auto file = fileutils::loadFile(activeCallsPath_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::lock_guard lk {activeCallsMtx_}; oh.get().convert(activeCalls_); } catch (const std::exception& e) { return; } } void saveActiveCalls() const { std::ofstream file(activeCallsPath_, std::ios::trunc | std::ios::binary); msgpack::pack(file, activeCalls_); } void loadHostedCalls() const { try { // read file auto file = fileutils::loadFile(hostedCallsPath_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::lock_guard lk {activeCallsMtx_}; oh.get().convert(hostedCalls_); } catch (const std::exception& e) { return; } } void saveHostedCalls() const { std::ofstream file(hostedCallsPath_, std::ios::trunc | std::ios::binary); msgpack::pack(file, hostedCalls_); } void voteUnban(const std::string& contactUri, const std::string_view type, const OnDoneCb& cb); std::vector<std::map<std::string, std::string>> getMembers(bool includeInvited, bool includeLeft, bool includeBanned) const; std::string_view bannedType(const std::string& uri) const { auto repo = repoPath(); auto crt = fmt::format("{}.crt", uri); auto bannedMember = repo / "banned" / "members" / crt; if (std::filesystem::is_regular_file(bannedMember)) return "members"sv; auto bannedAdmin = repo / "banned" / "admins" / crt; if (std::filesystem::is_regular_file(bannedAdmin)) return "admins"sv; auto bannedInvited = repo / "banned" / "invited" / uri; if (std::filesystem::is_regular_file(bannedInvited)) return "invited"sv; auto bannedDevice = repo / "banned" / "devices" / crt; if (std::filesystem::is_regular_file(bannedDevice)) return "devices"sv; return {}; } std::shared_ptr<dhtnet::ChannelSocket> gitSocket(const DeviceId& deviceId) const { auto deviceSockets = gitSocketList_.find(deviceId); return (deviceSockets != gitSocketList_.end()) ? deviceSockets->second : nullptr; } void addGitSocket(const DeviceId& deviceId, const std::shared_ptr<dhtnet::ChannelSocket>& socket) { gitSocketList_[deviceId] = socket; } void removeGitSocket(const DeviceId& deviceId) { auto deviceSockets = gitSocketList_.find(deviceId); if (deviceSockets != gitSocketList_.end()) gitSocketList_.erase(deviceSockets); } /** * Remove all git sockets and all DRT nodes associated with the given peer. * This is used when a swarm member is banned to ensure that we stop syncing * with them or sending them message notifications. */ void disconnectFromPeer(const std::string& peerUri); std::vector<std::map<std::string, std::string>> getMembers(bool includeInvited, bool includeLeft) const; std::mutex membersMtx_ {}; std::set<std::string> checkedMembers_; // Store members we tried std::function<void()> bootstrapCb_; #ifdef LIBJAMI_TESTABLE std::function<void(std::string, BootstrapStatus)> bootstrapCbTest_; #endif std::mutex writeMtx_ {}; std::unique_ptr<ConversationRepository> repository_; std::shared_ptr<SwarmManager> swarmManager_; std::weak_ptr<JamiAccount> account_; std::string accountId_ {}; std::string userId_; std::string deviceId_; std::atomic_bool isRemoving_ {false}; std::vector<std::map<std::string, std::string>> loadMessages(const LogOptions& options); std::vector<libjami::SwarmMessage> loadMessages2(const LogOptions& options, History* optHistory = nullptr); void pull(const std::string& deviceId); std::vector<std::map<std::string, std::string>> mergeHistory(const std::string& uri); // Avoid multiple fetch/merges at the same time. std::mutex pullcbsMtx_ {}; std::map<std::string, std::deque<std::pair<std::string, OnPullCb>>> fetchingRemotes_ {}; // store current remote in fetch std::shared_ptr<TransferManager> transferManager_ {}; std::filesystem::path conversationDataPath_ {}; std::filesystem::path fetchedPath_ {}; // Manage last message displayed and status std::filesystem::path sendingPath_ {}; std::filesystem::path preferencesPath_ {}; OnMembersChanged onMembersChanged_ {}; // Manage hosted calls on this device std::filesystem::path hostedCallsPath_ {}; mutable std::map<std::string, uint64_t /* start time */> hostedCalls_ {}; // Manage active calls for this conversation (can be hosted by other devices) std::filesystem::path activeCallsPath_ {}; mutable std::mutex activeCallsMtx_ {}; mutable std::vector<std::map<std::string, std::string>> activeCalls_ {}; GitSocketList gitSocketList_ {}; // Bootstrap std::shared_ptr<asio::io_context> ioContext_; std::unique_ptr<asio::steady_timer> fallbackTimer_; /** * Loaded history represents the linearized history to show for clients */ mutable History loadedHistory_ {}; std::vector<std::shared_ptr<libjami::SwarmMessage>> addToHistory( const std::vector<std::map<std::string, std::string>>& commits, bool messageReceived = false, bool commitFromSelf = false, History* history = nullptr) const; // While loading the history, we need to avoid: // - reloading history (can just be ignored) // - adding new commits (should wait for history to be loaded) bool isLoadingHistory_ {false}; mutable std::mutex historyMtx_ {}; mutable std::condition_variable historyCv_ {}; void handleReaction(History& history, const std::shared_ptr<libjami::SwarmMessage>& sharedCommit) const; void handleEdition(History& history, const std::shared_ptr<libjami::SwarmMessage>& sharedCommit, bool messageReceived) const; bool handleMessage(History& history, const std::shared_ptr<libjami::SwarmMessage>& sharedCommit, bool messageReceived) const; void rectifyStatus(const std::shared_ptr<libjami::SwarmMessage>& message, History& history) const; /** * {uri, { * {"fetch", "commitId"}, * {"fetched_ts", "timestamp"}, * {"read", "commitId"}, * {"read_ts", "timestamp"} * } * } */ mutable std::mutex messageStatusMtx_; std::function<void(const std::map<std::string, std::map<std::string, std::string>>&)> messageStatusCb_ {}; std::filesystem::path statusPath_ {}; mutable std::map<std::string, std::map<std::string, std::string>> messagesStatus_ {}; /** * Status: 0 = commited, 1 = fetched, 2 = read * This cache the curent status to add in the messages */ // Note: only store int32_t cause it's easy to pass to dbus this way // memberToStatus serves as a cache for loading messages mutable std::map<std::string, int32_t> memberToStatus; // futureStatus is used to store the status for receiving messages // (because we're not sure to fetch the commit before receiving a status change for this) mutable std::map<std::string, std::map<std::string, int32_t>> futureStatus; // Update internal structures regarding status void updateStatus(const std::string& uri, libjami::Account::MessageStates status, const std::string& commitId, const std::string& ts, bool emit = false); std::shared_ptr<Typers> typers_; }; bool Conversation::Impl::isAdmin() const { auto adminsPath = repoPath() / "admins"; return std::filesystem::is_regular_file(fileutils::getFullPath(adminsPath, userId_ + ".crt")); } void Conversation::Impl::disconnectFromPeer(const std::string& peerUri) { // Remove nodes from swarmManager const auto nodes = swarmManager_->getRoutingTable().getAllNodes(); std::vector<NodeId> toRemove; for (const auto node : nodes) if (peerUri == repository_->uriFromDevice(node.toString())) toRemove.emplace_back(node); swarmManager_->deleteNode(toRemove); // Remove git sockets with this member for (auto it = gitSocketList_.begin(); it != gitSocketList_.end();) { if (peerUri == repository_->uriFromDevice(it->first.toString())) it = gitSocketList_.erase(it); else ++it; } } std::vector<std::map<std::string, std::string>> Conversation::Impl::getMembers(bool includeInvited, bool includeLeft, bool includeBanned) const { std::vector<std::map<std::string, std::string>> result; auto members = repository_->members(); std::lock_guard lk(messageStatusMtx_); for (const auto& member : members) { if (member.role == MemberRole::BANNED && !includeBanned) { continue; } if (member.role == MemberRole::INVITED && !includeInvited) continue; if (member.role == MemberRole::LEFT && !includeLeft) continue; auto mm = member.map(); mm[ConversationMapKeys::LAST_DISPLAYED] = messagesStatus_[member.uri]["read"]; result.emplace_back(std::move(mm)); } return result; } std::vector<std::string> Conversation::Impl::commitsEndedCalls() { // Handle current calls std::vector<std::string> commits {}; std::unique_lock lk(writeMtx_); std::unique_lock lkA(activeCallsMtx_); for (const auto& hostedCall : hostedCalls_) { // In this case, this means that we left // the conference while still hosting it, so activeCalls // will not be correctly updated // We don't need to send notifications there, as peers will sync with presence Json::Value value; value["uri"] = userId_; value["device"] = deviceId_; value["confId"] = hostedCall.first; value["type"] = "application/call-history+json"; auto now = std::chrono::system_clock::now(); auto nowConverted = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()) .count(); value["duration"] = std::to_string((nowConverted - hostedCall.second) * 1000); auto itActive = std::find_if(activeCalls_.begin(), activeCalls_.end(), [this, confId = hostedCall.first](const auto& value) { return value.at("id") == confId && value.at("uri") == userId_ && value.at("device") == deviceId_; }); if (itActive != activeCalls_.end()) activeCalls_.erase(itActive); commits.emplace_back(repository_->commitMessage(Json::writeString(jsonBuilder, value))); JAMI_DEBUG("Removing hosted conference... {:s}", hostedCall.first); } hostedCalls_.clear(); saveActiveCalls(); saveHostedCalls(); return commits; } std::filesystem::path Conversation::Impl::repoPath() const { return fileutils::get_data_dir() / accountId_ / "conversations" / repository_->id(); } std::vector<std::map<std::string, std::string>> Conversation::Impl::loadMessages(const LogOptions& options) { if (!repository_) return {}; std::vector<ConversationCommit> commits; auto startLogging = options.from == ""; auto breakLogging = false; repository_->log( [&](const auto& id, const auto& author, const auto& commit) { if (!commits.empty()) { // Set linearized parent commits.rbegin()->linearized_parent = id; } if (options.skipMerge && git_commit_parentcount(commit.get()) > 1) { return CallbackResult::Skip; } if ((options.nbOfCommits != 0 && commits.size() == options.nbOfCommits)) return CallbackResult::Break; // Stop logging if (breakLogging) return CallbackResult::Break; // Stop logging if (id == options.to) { if (options.includeTo) breakLogging = true; // For the next commit else return CallbackResult::Break; // Stop logging } if (!startLogging && options.from != "" && options.from == id) startLogging = true; if (!startLogging) return CallbackResult::Skip; // Start logging after this one if (options.fastLog) { if (options.authorUri != "") { if (options.authorUri == repository_->uriFromDevice(author.email)) { return CallbackResult::Break; // Found author, stop } } // Used to only count commit commits.emplace(commits.end(), ConversationCommit {}); return CallbackResult::Skip; } return CallbackResult::Ok; // Continue }, [&](auto&& cc) { commits.emplace(commits.end(), std::forward<decltype(cc)>(cc)); }, [](auto, auto, auto) { return false; }, options.from, options.logIfNotFound); return repository_->convCommitsToMap(commits); } std::vector<libjami::SwarmMessage> Conversation::Impl::loadMessages2(const LogOptions& options, History* optHistory) { if (!optHistory) { std::lock_guard lock(historyMtx_); if (!repository_ || isLoadingHistory_) return {}; isLoadingHistory_ = true; } // Reset variables if needed to get the correct status. // options.from stores a swarmMessageId; this option is used // to load the messages of a conversation from a specific message if (options.from.empty()) { memberToStatus.clear(); } // By convention, if options.nbOfCommits is zero, then we // don't impose a limit on the number of commits returned. bool limitNbOfCommits = options.nbOfCommits > 0; auto startLogging = options.from == ""; auto breakLogging = false; auto currentHistorySize = loadedHistory_.messageList.size(); std::vector<std::string> replies; std::vector<std::shared_ptr<libjami::SwarmMessage>> msgList; repository_->log( /* preCondition */ [&](const auto& id, const auto& author, const auto& commit) { if (options.skipMerge && git_commit_parentcount(commit.get()) > 1) { return CallbackResult::Skip; } if (replies.empty()) { // This avoid load until // NOTE: in the future, we may want to add "Reply-Body" in commit to avoid to load // until this commit if ((limitNbOfCommits && (loadedHistory_.messageList.size() - currentHistorySize) == options.nbOfCommits)) return CallbackResult::Break; // Stop logging if (breakLogging) return CallbackResult::Break; // Stop logging if (id == options.to) { if (options.includeTo) breakLogging = true; // For the next commit else return CallbackResult::Break; // Stop logging } } if (!startLogging && options.from != "" && options.from == id) startLogging = true; if (!startLogging) return CallbackResult::Skip; // Start logging after this one if (options.fastLog) { if (options.authorUri != "") { if (options.authorUri == repository_->uriFromDevice(author.email)) { return CallbackResult::Break; // Found author, stop } } } return CallbackResult::Ok; // Continue }, /* emplaceCb */ [&](auto&& cc) { if(limitNbOfCommits && (msgList.size() == options.nbOfCommits)) return; auto optMessage = repository_->convCommitToMap(cc); if (!optMessage.has_value()) return; auto message = optMessage.value(); if (message.find("reply-to") != message.end()) { replies.emplace_back(message.at("reply-to")); } auto it = std::find(replies.begin(), replies.end(), message.at("id")); if (it != replies.end()) { replies.erase(it); } std::shared_ptr<libjami::SwarmMessage> firstMsg; if (!optHistory && msgList.empty() && !loadedHistory_.messageList.empty()) { firstMsg = *loadedHistory_.messageList.rbegin(); } auto added = addToHistory({message}, false, false, optHistory); if (!added.empty() && firstMsg) { emitSignal<libjami::ConversationSignal::SwarmMessageUpdated>(accountId_, repository_->id(), *firstMsg); } msgList.insert(msgList.end(), added.begin(), added.end()); }, /* postCondition */ [&](auto, auto, auto) { // Stop logging if there was a limit set on the number of commits // to return and we reached it. This isn't strictly necessary since // the check at the beginning of `emplaceCb` ensures that we won't // return too many messages, but it prevents us from needlessly // iterating over a (potentially) large number of commits. return limitNbOfCommits && (msgList.size() == options.nbOfCommits); }, options.from, options.logIfNotFound); // Convert for client (remove ptr) std::vector<libjami::SwarmMessage> ret; ret.reserve(msgList.size()); for (const auto& msg: msgList) { ret.emplace_back(*msg); } if (!optHistory) { std::lock_guard lock(historyMtx_); isLoadingHistory_ = false; historyCv_.notify_all(); } return ret; } void Conversation::Impl::handleReaction(History& history, const std::shared_ptr<libjami::SwarmMessage>& sharedCommit) const { auto it = history.quickAccess.find(sharedCommit->body.at("react-to")); auto peditIt = history.pendingEditions.find(sharedCommit->id); if (peditIt != history.pendingEditions.end()) { auto oldBody = sharedCommit->body; sharedCommit->body["body"] = peditIt->second.front()->body["body"]; if (sharedCommit->body.at("body").empty()) return; history.pendingEditions.erase(peditIt); } if (it != history.quickAccess.end()) { it->second->reactions.emplace_back(sharedCommit->body); emitSignal<libjami::ConversationSignal::ReactionAdded>(accountId_, repository_->id(), it->second->id, sharedCommit->body); } else { history.pendingReactions[sharedCommit->body.at("react-to")].emplace_back(sharedCommit->body); } } void Conversation::Impl::handleEdition(History& history, const std::shared_ptr<libjami::SwarmMessage>& sharedCommit, bool messageReceived) const { auto editId = sharedCommit->body.at("edit"); auto it = history.quickAccess.find(editId); if (it != history.quickAccess.end()) { auto baseCommit = it->second; if (baseCommit) { auto itReact = baseCommit->body.find("react-to"); std::string toReplace = (baseCommit->type == "application/data-transfer+json") ? "tid" : "body"; auto body = sharedCommit->body.at(toReplace); // Edit reaction if (itReact != baseCommit->body.end()) { baseCommit->body[toReplace] = body; // Replace body if pending it = history.quickAccess.find(itReact->second); auto itPending = history.pendingReactions.find(itReact->second); if (it != history.quickAccess.end()) { baseCommit = it->second; // Base commit auto itPreviousReact = std::find_if(baseCommit->reactions.begin(), baseCommit->reactions.end(), [&](const auto& reaction) { return reaction.at("id") == editId; }); if (itPreviousReact != baseCommit->reactions.end()) { (*itPreviousReact)[toReplace] = body; if (body.empty()) { baseCommit->reactions.erase(itPreviousReact); emitSignal<libjami::ConversationSignal::ReactionRemoved>(accountId_, repository_ ->id(), baseCommit->id, editId); } } } else if (itPending != history.pendingReactions.end()) { // Else edit if pending auto itReaction = std::find_if(itPending->second.begin(), itPending->second.end(), [&](const auto& reaction) { return reaction.at("id") == editId; }); if (itReaction != itPending->second.end()) { (*itReaction)[toReplace] = body; if (body.empty()) itPending->second.erase(itReaction); } } else { // Add to pending edtions messageReceived ? history.pendingEditions[editId].emplace_front(sharedCommit) : history.pendingEditions[editId].emplace_back(sharedCommit); } } else { // Normal message it->second->editions.emplace(it->second->editions.begin(), it->second->body); it->second->body[toReplace] = sharedCommit->body[toReplace]; if (toReplace == "tid") { // Avoid to replace fileId in client it->second->body["fileId"] = ""; } // Remove reactions if (sharedCommit->body.at(toReplace).empty()) it->second->reactions.clear(); emitSignal<libjami::ConversationSignal::SwarmMessageUpdated>(accountId_, repository_->id(), *it->second); } } } else { messageReceived ? history.pendingEditions[editId].emplace_front(sharedCommit) : history.pendingEditions[editId].emplace_back(sharedCommit); } } bool Conversation::Impl::handleMessage(History& history, const std::shared_ptr<libjami::SwarmMessage>& sharedCommit, bool messageReceived) const { if (messageReceived) { // For a received message, we place it at the beginning of the list if (!history.messageList.empty()) sharedCommit->linearizedParent = (*history.messageList.begin())->id; history.messageList.emplace_front(sharedCommit); } else { // For a loaded message, we load from newest to oldest // So we change the parent of the last message. if (!history.messageList.empty()) (*history.messageList.rbegin())->linearizedParent = sharedCommit->id; history.messageList.emplace_back(sharedCommit); } // Handle pending reactions/editions auto reactIt = history.pendingReactions.find(sharedCommit->id); if (reactIt != history.pendingReactions.end()) { for (const auto& commitBody : reactIt->second) sharedCommit->reactions.emplace_back(commitBody); history.pendingReactions.erase(reactIt); } auto peditIt = history.pendingEditions.find(sharedCommit->id); if (peditIt != history.pendingEditions.end()) { auto oldBody = sharedCommit->body; if (sharedCommit->type == "application/data-transfer+json") { sharedCommit->body["tid"] = peditIt->second.front()->body["tid"]; sharedCommit->body["fileId"] = ""; } else { sharedCommit->body["body"] = peditIt->second.front()->body["body"]; } peditIt->second.pop_front(); for (const auto& commit : peditIt->second) { sharedCommit->editions.emplace_back(commit->body); } sharedCommit->editions.emplace_back(oldBody); history.pendingEditions.erase(peditIt); } // Announce to client if (messageReceived) emitSignal<libjami::ConversationSignal::SwarmMessageReceived>(accountId_, repository_->id(), *sharedCommit); return !messageReceived; } void Conversation::Impl::rectifyStatus(const std::shared_ptr<libjami::SwarmMessage>& message, History& history) const { auto parentIt = history.quickAccess.find(message->linearizedParent); auto currentMessage = message; while(parentIt != history.quickAccess.end()){ const auto& parent = parentIt->second; for (const auto& [peer, value] : message->status) { auto parentStatusIt = parent->status.find(peer); if (parentStatusIt == parent->status.end() || parentStatusIt->second < value) { parent->status[peer] = value; emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>( accountId_, repository_->id(), peer, parent->id, value); } else if(parentStatusIt->second >= value){ break; } } currentMessage = parent; parentIt = history.quickAccess.find(parent->linearizedParent); } } std::vector<std::shared_ptr<libjami::SwarmMessage>> Conversation::Impl::addToHistory(const std::vector<std::map<std::string, std::string>>& commits, bool messageReceived, bool commitFromSelf, History* optHistory) const { auto acc = account_.lock(); if (!acc) return {}; auto username = acc->getUsername(); if (messageReceived && (!optHistory && isLoadingHistory_)) { std::unique_lock lk(historyMtx_); historyCv_.wait(lk, [&] { return !isLoadingHistory_; }); } std::vector<std::shared_ptr<libjami::SwarmMessage>> messages; auto addCommit = [&](const auto& commit) { auto* history = optHistory ? optHistory : &loadedHistory_; auto commitId = commit.at("id"); if (history->quickAccess.find(commitId) != history->quickAccess.end()) return; // Already present auto typeIt = commit.find("type"); auto reactToIt = commit.find("react-to"); auto editIt = commit.find("edit"); // Nothing to show for the client, skip if (typeIt != commit.end() && typeIt->second == "merge") return; auto sharedCommit = std::make_shared<libjami::SwarmMessage>(); sharedCommit->fromMapStringString(commit); // Set message status based on cache (only on history for client) if (!commitFromSelf && optHistory == nullptr) { std::lock_guard lk(messageStatusMtx_); for (const auto& member: repository_->members()) { // If we have a status cached, use it auto itFuture = futureStatus.find(sharedCommit->id); if (itFuture != futureStatus.end()) { sharedCommit->status = std::move(itFuture->second); futureStatus.erase(itFuture); continue; } // Else we need to compute the status. auto& cache = memberToStatus[member.uri]; if (cache == 0) { // Message is sending, sent or displayed cache = static_cast<int32_t>(libjami::Account::MessageStates::SENDING); } if (!messageReceived) { // For loading previous messages, there is 3 cases. Last value cached is displayed, so is every previous commits // Else, if last value is sent, we can compare to the last read commit to update the cache // Finally if it's sending, we check last fetched commit if (cache == static_cast<int32_t>(libjami::Account::MessageStates::SENT)) { if (messagesStatus_[member.uri]["read"] == sharedCommit->id) { cache = static_cast<int32_t>(libjami::Account::MessageStates::DISPLAYED); } } else if (cache <= static_cast<int32_t>(libjami::Account::MessageStates::SENDING)) { // SENDING or UNKNOWN // cache can be upgraded to displayed or sent if (messagesStatus_[member.uri]["read"] == sharedCommit->id) { cache = static_cast<int32_t>(libjami::Account::MessageStates::DISPLAYED); } else if (messagesStatus_[member.uri]["fetched"] == sharedCommit->id) { cache = static_cast<int32_t>(libjami::Account::MessageStates::SENT); } } if(static_cast<int32_t>(cache) > sharedCommit->status[member.uri]){ sharedCommit->status[member.uri] = static_cast<int32_t>(cache); } } else { // If member is author of the message received, they already saw it if (member.uri == commit.at("author")) { // If member is the author of the commit, they are considered as displayed (same for all previous commits) messagesStatus_[member.uri]["read"] = sharedCommit->id; messagesStatus_[member.uri]["fetched"] = sharedCommit->id; sharedCommit->status[commit.at("author")] = static_cast<int32_t>(libjami::Account::MessageStates::DISPLAYED); cache = static_cast<int32_t>(libjami::Account::MessageStates::DISPLAYED); continue; } // For receiving messages, every commit is considered as SENDING, unless we got a update auto status = static_cast<int32_t>(libjami::Account::MessageStates::SENDING); if (messagesStatus_[member.uri]["read"] == sharedCommit->id) { status = static_cast<int32_t>(libjami::Account::MessageStates::DISPLAYED); } else if (messagesStatus_[member.uri]["fetched"] == sharedCommit->id) { status = static_cast<int32_t>(libjami::Account::MessageStates::SENT); } if(static_cast<int32_t>(status) > sharedCommit->status[member.uri]){ sharedCommit->status[member.uri] = static_cast<int32_t>(status); } } } } history->quickAccess[commitId] = sharedCommit; if (reactToIt != commit.end() && !reactToIt->second.empty()) { handleReaction(*history, sharedCommit); } else if (editIt != commit.end() && !editIt->second.empty()) { handleEdition(*history, sharedCommit, messageReceived); } else if (handleMessage(*history, sharedCommit, messageReceived)) { messages.emplace_back(sharedCommit); } rectifyStatus(sharedCommit, *history); }; std::for_each(commits.begin(), commits.end(), addCommit); return messages; } Conversation::Conversation(const std::shared_ptr<JamiAccount>& account, ConversationMode mode, const std::string& otherMember) : pimpl_ {new Impl {account, mode, otherMember}} {} Conversation::Conversation(const std::shared_ptr<JamiAccount>& account, const std::string& conversationId) : pimpl_ {new Impl {account, conversationId}} {} Conversation::Conversation(const std::shared_ptr<JamiAccount>& account, const std::string& remoteDevice, const std::string& conversationId) : pimpl_ {new Impl {account, remoteDevice, conversationId}} {} Conversation::~Conversation() {} std::string Conversation::id() const { return pimpl_->repository_ ? pimpl_->repository_->id() : ""; } void Conversation::addMember(const std::string& contactUri, const OnDoneCb& cb) { try { if (mode() == ConversationMode::ONE_TO_ONE) { // Only authorize to add left members auto initialMembers = getInitialMembers(); auto it = std::find(initialMembers.begin(), initialMembers.end(), contactUri); if (it == initialMembers.end()) { JAMI_WARN("Unable to add new member in one to one conversation"); cb(false, ""); return; } } } catch (const std::exception& e) { JAMI_WARN("Unable to get mode: %s", e.what()); cb(false, ""); return; } if (isMember(contactUri, true)) { JAMI_WARN("Unable to add member %s because it's already a member", contactUri.c_str()); cb(false, ""); return; } if (isBanned(contactUri)) { if (pimpl_->isAdmin()) { dht::ThreadPool::io().run( [w = weak(), contactUri = std::move(contactUri), cb = std::move(cb)] { if (auto sthis = w.lock()) { auto members = sthis->pimpl_->repository_->members(); auto type = sthis->pimpl_->bannedType(contactUri); if (type.empty()) { cb(false, {}); return; } sthis->pimpl_->voteUnban(contactUri, type, cb); } }); } else { JAMI_WARN("Unable to add member %s because this member is blocked", contactUri.c_str()); cb(false, ""); } return; } dht::ThreadPool::io().run([w = weak(), contactUri = std::move(contactUri), cb = std::move(cb)] { if (auto sthis = w.lock()) { // Add member files and commit std::unique_lock lk(sthis->pimpl_->writeMtx_); auto commit = sthis->pimpl_->repository_->addMember(contactUri); sthis->pimpl_->announce(commit, true); lk.unlock(); if (cb) cb(!commit.empty(), commit); } }); } std::shared_ptr<dhtnet::ChannelSocket> Conversation::gitSocket(const DeviceId& deviceId) const { return pimpl_->gitSocket(deviceId); } void Conversation::addGitSocket(const DeviceId& deviceId, const std::shared_ptr<dhtnet::ChannelSocket>& socket) { pimpl_->addGitSocket(deviceId, socket); } void Conversation::removeGitSocket(const DeviceId& deviceId) { pimpl_->removeGitSocket(deviceId); } void Conversation::shutdownConnections() { pimpl_->fallbackTimer_->cancel(); pimpl_->gitSocketList_.clear(); if (pimpl_->swarmManager_) pimpl_->swarmManager_->shutdown(); std::lock_guard(pimpl_->membersMtx_); pimpl_->checkedMembers_.clear(); } void Conversation::connectivityChanged() { if (pimpl_->swarmManager_) pimpl_->swarmManager_->maintainBuckets(); } std::vector<jami::DeviceId> Conversation::getDeviceIdList() const { return pimpl_->swarmManager_->getRoutingTable().getAllNodes(); } std::shared_ptr<Typers> Conversation::typers() const { return pimpl_->typers_; } bool Conversation::hasSwarmChannel(const std::string& deviceId) { if (!pimpl_->swarmManager_) return false; return pimpl_->swarmManager_->isConnectedWith(DeviceId(deviceId)); } void Conversation::Impl::voteUnban(const std::string& contactUri, const std::string_view type, const OnDoneCb& cb) { // Check if admin if (!isAdmin()) { JAMI_WARN("You're not an admin of this repo. Unable to unblock %s", contactUri.c_str()); cb(false, {}); return; } // Vote for removal std::unique_lock lk(writeMtx_); auto voteCommit = repository_->voteUnban(contactUri, type); if (voteCommit.empty()) { JAMI_WARN("Unbanning %s failed", contactUri.c_str()); cb(false, ""); return; } auto lastId = voteCommit; std::vector<std::string> commits; commits.emplace_back(voteCommit); // If admin, check vote auto resolveCommit = repository_->resolveVote(contactUri, type, "unban"); if (!resolveCommit.empty()) { commits.emplace_back(resolveCommit); lastId = resolveCommit; JAMI_WARN("Vote solved for unbanning %s.", contactUri.c_str()); } announce(commits, true); lk.unlock(); if (cb) cb(!lastId.empty(), lastId); } void Conversation::removeMember(const std::string& contactUri, bool isDevice, const OnDoneCb& cb) { dht::ThreadPool::io().run([w = weak(), contactUri = std::move(contactUri), isDevice = std::move(isDevice), cb = std::move(cb)] { if (auto sthis = w.lock()) { // Check if admin if (!sthis->pimpl_->isAdmin()) { JAMI_WARN("You're not an admin of this repo. Unable to block %s", contactUri.c_str()); cb(false, {}); return; } // Get current user type std::string type; if (isDevice) { type = "devices"; } else { auto members = sthis->pimpl_->repository_->members(); for (const auto& member : members) { if (member.uri == contactUri) { if (member.role == MemberRole::INVITED) { type = "invited"; } else if (member.role == MemberRole::ADMIN) { type = "admins"; } else if (member.role == MemberRole::MEMBER) { type = "members"; } break; } } if (type.empty()) { cb(false, {}); return; } } // Vote for removal std::unique_lock lk(sthis->pimpl_->writeMtx_); auto voteCommit = sthis->pimpl_->repository_->voteKick(contactUri, type); if (voteCommit.empty()) { JAMI_WARN("Kicking %s failed", contactUri.c_str()); cb(false, ""); return; } auto lastId = voteCommit; std::vector<std::string> commits; commits.emplace_back(voteCommit); // If admin, check vote auto resolveCommit = sthis->pimpl_->repository_->resolveVote(contactUri, type, "ban"); if (!resolveCommit.empty()) { commits.emplace_back(resolveCommit); lastId = resolveCommit; JAMI_WARN("Vote solved for %s. %s banned", contactUri.c_str(), isDevice ? "Device" : "Member"); sthis->pimpl_->disconnectFromPeer(contactUri); } sthis->pimpl_->announce(commits, true); lk.unlock(); cb(!lastId.empty(), lastId); } }); } std::vector<std::map<std::string, std::string>> Conversation::getMembers(bool includeInvited, bool includeLeft, bool includeBanned) const { return pimpl_->getMembers(includeInvited, includeLeft, includeBanned); } std::set<std::string> Conversation::memberUris(std::string_view filter, const std::set<MemberRole>& filteredRoles) const { return pimpl_->repository_->memberUris(filter, filteredRoles); } std::vector<NodeId> Conversation::peersToSyncWith() const { const auto& routingTable = pimpl_->swarmManager_->getRoutingTable(); const auto& nodes = routingTable.getNodes(); const auto& mobiles = routingTable.getMobileNodes(); std::vector<NodeId> s; s.reserve(nodes.size() + mobiles.size()); s.insert(s.end(), nodes.begin(), nodes.end()); s.insert(s.end(), mobiles.begin(), mobiles.end()); for (const auto& [deviceId, _] : pimpl_->gitSocketList_) if (std::find(s.cbegin(), s.cend(), deviceId) == s.cend()) s.emplace_back(deviceId); return s; } bool Conversation::isBootstraped() const { const auto& routingTable = pimpl_->swarmManager_->getRoutingTable(); return !routingTable.getNodes().empty(); } std::string Conversation::uriFromDevice(const std::string& deviceId) const { return pimpl_->repository_->uriFromDevice(deviceId); } void Conversation::monitor() { pimpl_->swarmManager_->getRoutingTable().printRoutingTable(); } std::string Conversation::join() { return pimpl_->repository_->join(); } bool Conversation::isMember(const std::string& uri, bool includeInvited) const { auto repoPath = pimpl_->repoPath(); auto invitedPath = repoPath / "invited"; auto adminsPath = repoPath / "admins"; auto membersPath = repoPath / "members"; std::vector<std::filesystem::path> pathsToCheck = {adminsPath, membersPath}; if (includeInvited) pathsToCheck.emplace_back(invitedPath); for (const auto& path : pathsToCheck) { for (const auto& certificate : dhtnet::fileutils::readDirectory(path)) { std::string_view crtUri = certificate; auto crtIt = crtUri.find(".crt"); if (path != invitedPath && crtIt == std::string_view::npos) { JAMI_WARNING("Incorrect file found: {}/{}", path, certificate); continue; } if (crtIt != std::string_view::npos) crtUri = crtUri.substr(0, crtIt); if (crtUri == uri) return true; } } if (includeInvited && mode() == ConversationMode::ONE_TO_ONE) { for (const auto& member : getInitialMembers()) { if (member == uri) return true; } } return false; } bool Conversation::isBanned(const std::string& uri) const { return !pimpl_->bannedType(uri).empty(); } void Conversation::sendMessage(std::string&& message, const std::string& type, const std::string& replyTo, OnCommitCb&& onCommit, OnDoneCb&& cb) { Json::Value json; json["body"] = std::move(message); json["type"] = type; sendMessage(std::move(json), replyTo, std::move(onCommit), std::move(cb)); } void Conversation::sendMessage(Json::Value&& value, const std::string& replyTo, OnCommitCb&& onCommit, OnDoneCb&& cb) { if (!replyTo.empty()) { auto commit = pimpl_->repository_->getCommit(replyTo); if (commit == std::nullopt) { JAMI_ERR("Replying to invalid commit %s", replyTo.c_str()); return; } value["reply-to"] = replyTo; } dht::ThreadPool::io().run( [w = weak(), value = std::move(value), onCommit = std::move(onCommit), cb = std::move(cb)] { if (auto sthis = w.lock()) { std::unique_lock lk(sthis->pimpl_->writeMtx_); auto commit = sthis->pimpl_->repository_->commitMessage( Json::writeString(jsonBuilder, value)); lk.unlock(); if (onCommit) onCommit(commit); sthis->pimpl_->announce(commit, true); if (cb) cb(!commit.empty(), commit); } }); } void Conversation::sendMessages(std::vector<Json::Value>&& messages, OnMultiDoneCb&& cb) { dht::ThreadPool::io().run([w = weak(), messages = std::move(messages), cb = std::move(cb)] { if (auto sthis = w.lock()) { std::vector<std::string> commits; commits.reserve(messages.size()); std::unique_lock lk(sthis->pimpl_->writeMtx_); for (const auto& message : messages) { auto commit = sthis->pimpl_->repository_->commitMessage( Json::writeString(jsonBuilder, message)); commits.emplace_back(std::move(commit)); } lk.unlock(); sthis->pimpl_->announce(commits, true); if (cb) cb(commits); } }); } std::optional<std::map<std::string, std::string>> Conversation::getCommit(const std::string& commitId) const { auto commit = pimpl_->repository_->getCommit(commitId); if (commit == std::nullopt) return std::nullopt; return pimpl_->repository_->convCommitToMap(*commit); } void Conversation::loadMessages(OnLoadMessages cb, const LogOptions& options) { if (!cb) return; dht::ThreadPool::io().run([w = weak(), cb = std::move(cb), options] { if (auto sthis = w.lock()) { cb(sthis->pimpl_->loadMessages(options)); } }); } void Conversation::loadMessages2(const OnLoadMessages2& cb, const LogOptions& options) { if (!cb) return; dht::ThreadPool::io().run([w = weak(), cb = std::move(cb), options] { if (auto sthis = w.lock()) { cb(sthis->pimpl_->loadMessages2(options)); } }); } void Conversation::clearCache() { pimpl_->loadedHistory_.messageList.clear(); pimpl_->loadedHistory_.quickAccess.clear(); pimpl_->loadedHistory_.pendingEditions.clear(); pimpl_->loadedHistory_.pendingReactions.clear(); } std::string Conversation::lastCommitId() const { LogOptions options; options.nbOfCommits = 1; options.skipMerge = true; History optHistory; { std::lock_guard lk(pimpl_->historyMtx_); if (!pimpl_->loadedHistory_.messageList.empty()) return (*pimpl_->loadedHistory_.messageList.begin())->id; } std::lock_guard lk(pimpl_->writeMtx_); auto res = pimpl_->loadMessages2(options, &optHistory); if (res.empty()) return {}; return (*optHistory.messageList.begin())->id; } std::vector<std::map<std::string, std::string>> Conversation::Impl::mergeHistory(const std::string& uri) { if (not repository_) { JAMI_WARN("Invalid repo. Abort merge"); return {}; } auto remoteHead = repository_->remoteHead(uri); if (remoteHead.empty()) { JAMI_WARN("Unable to get HEAD of %s", uri.c_str()); return {}; } // Validate commit auto [newCommits, err] = repository_->validFetch(uri); if (newCommits.empty()) { if (err) JAMI_ERR("Unable to validate history with %s", uri.c_str()); repository_->removeBranchWith(uri); return {}; } // If validated, merge auto [ok, cid] = repository_->merge(remoteHead); if (!ok) { JAMI_ERR("Unable to merge history with %s", uri.c_str()); repository_->removeBranchWith(uri); return {}; } if (!cid.empty()) { // A merge commit was generated, should be added in new commits auto commit = repository_->getCommit(cid); if (commit != std::nullopt) newCommits.emplace_back(*commit); } JAMI_DEBUG("Successfully merge history with {:s}", uri); auto result = repository_->convCommitsToMap(newCommits); for (auto& commit : result) { auto it = commit.find("type"); if (it != commit.end() && it->second == "member") { repository_->refreshMembers(); if (commit["action"] == "ban") disconnectFromPeer(commit["uri"]); } } return result; } bool Conversation::pull(const std::string& deviceId, OnPullCb&& cb, std::string commitId) { std::lock_guard lk(pimpl_->pullcbsMtx_); auto [it, notInProgress] = pimpl_->fetchingRemotes_.emplace(deviceId, std::deque<std::pair<std::string, OnPullCb>>()); auto& pullcbs = it->second; auto itPull = std::find_if(pullcbs.begin(), pullcbs.end(), [&](const auto& elem) { return std::get<0>(elem) == commitId; }); if (itPull != pullcbs.end()) { JAMI_DEBUG("Ignoring request to pull from {:s} with commit {:s}: pull already in progress", deviceId, commitId); cb(false); return false; } JAMI_DEBUG("Pulling from {:s} with commit {:s}", deviceId, commitId); pullcbs.emplace_back(std::move(commitId), std::move(cb)); if (notInProgress) dht::ThreadPool::io().run([w = weak(), deviceId] { if (auto sthis_ = w.lock()) sthis_->pimpl_->pull(deviceId); }); return true; } void Conversation::Impl::pull(const std::string& deviceId) { auto& repo = repository_; std::string commitId; OnPullCb cb; while (true) { { std::lock_guard lk(pullcbsMtx_); auto it = fetchingRemotes_.find(deviceId); if (it == fetchingRemotes_.end()) { JAMI_ERROR("Could not find device {:s} in fetchingRemotes", deviceId); break; } auto& pullcbs = it->second; if (pullcbs.empty()) { fetchingRemotes_.erase(it); break; } auto& elem = pullcbs.front(); commitId = std::move(std::get<0>(elem)); cb = std::move(std::get<1>(elem)); pullcbs.pop_front(); } // If recently fetched, the commit can already be there, so no need to do complex operations if (commitId != "" && repo->getCommit(commitId, false) != std::nullopt) { cb(true); continue; } // Pull from remote auto fetched = repo->fetch(deviceId); if (!fetched) { cb(false); continue; } auto oldHead = repo->getHead(); std::string newHead = oldHead; std::unique_lock lk(writeMtx_); auto commits = mergeHistory(deviceId); if (!commits.empty()) { newHead = commits.rbegin()->at("id"); // Note: Because clients needs to linearize the history, they need to know all commits // that can be updated. // In this case, all commits until the common merge base should be announced. // The client ill need to update it's model after this. std::string mergeBase = oldHead; // If fast-forward, the merge base is the previous head auto newHeadCommit = repo->getCommit(newHead); if (newHeadCommit != std::nullopt && newHeadCommit->parents.size() > 1) { mergeBase = repo->mergeBase(newHeadCommit->parents[0], newHeadCommit->parents[1]); LogOptions options; options.to = mergeBase; auto updatedCommits = loadMessages(options); // We announce commits from oldest to update to newest. This generally avoid // to get detached commits until they are all announced. std::reverse(std::begin(updatedCommits), std::end(updatedCommits)); announce(updatedCommits); } else { announce(commits); } } lk.unlock(); bool commitFound = false; if (commitId != "") { // If `commitId` is non-empty, then we were trying to pull a specific commit. // We need to check if we actually got it; the fact that the fetch above was // successful doesn't guarantee that we did. for (const auto& commit : commits) { if (commit.at("id") == commitId) { commitFound = true; break; } } } else { commitFound = true; } if (!commitFound) JAMI_WARNING("Successfully fetched from device {} but didn't receive expected commit {}", deviceId, commitId); // WARNING: If its argument is `true`, this callback will try to send a message notification // for commit `commitId` to other members of the swarm. It's important that we only // send these notifications if we actually have the commit. Otherwise, we can end up // in a situation where the members of the swarm keep sending notifications to each // other for a commit that none of them have (note that we cannot rule this out, as // nothing prevents a malicious user from intentionally sending a notification with // a fake commit ID). if (cb) cb(commitFound); // Announce if profile changed if (oldHead != newHead) { auto diffStats = repo->diffStats(newHead, oldHead); auto changedFiles = repo->changedFiles(diffStats); if (find(changedFiles.begin(), changedFiles.end(), "profile.vcf") != changedFiles.end()) { emitSignal<libjami::ConversationSignal::ConversationProfileUpdated>( accountId_, repo->id(), repo->infos()); } } } } void Conversation::sync(const std::string& member, const std::string& deviceId, OnPullCb&& cb, std::string commitId) { pull(deviceId, std::move(cb), commitId); dht::ThreadPool::io().run([member, deviceId, w = weak_from_this()] { auto sthis = w.lock(); // For waiting request, downloadFile for (const auto& wr : sthis->dataTransfer()->waitingRequests()) { auto path = fileutils::get_data_dir() / sthis->pimpl_->accountId_ / "conversation_data" / sthis->id() / wr.fileId; auto start = fileutils::size(path); if (start < 0) start = 0; sthis->downloadFile(wr.interactionId, wr.fileId, wr.path, member, deviceId, start); } }); } std::map<std::string, std::string> Conversation::generateInvitation() const { // Invite the new member to the conversation Json::Value root; auto& metadata = root[ConversationMapKeys::METADATAS]; for (const auto& [k, v] : infos()) { if (v.size() >= 64000) { JAMI_WARNING("Cutting invite because the SIP message will be too long"); continue; } metadata[k] = v; } root[ConversationMapKeys::CONVERSATIONID] = id(); return {{"application/invite+json", Json::writeString(jsonBuilder, root)}}; } std::string Conversation::leave() { setRemovingFlag(); std::lock_guard lk(pimpl_->writeMtx_); return pimpl_->repository_->leave(); } void Conversation::setRemovingFlag() { pimpl_->isRemoving_ = true; } bool Conversation::isRemoving() { return pimpl_->isRemoving_; } void Conversation::erase() { if (pimpl_->conversationDataPath_ != "") dhtnet::fileutils::removeAll(pimpl_->conversationDataPath_, true); if (!pimpl_->repository_) return; std::lock_guard lk(pimpl_->writeMtx_); pimpl_->repository_->erase(); } ConversationMode Conversation::mode() const { return pimpl_->repository_->mode(); } std::vector<std::string> Conversation::getInitialMembers() const { return pimpl_->repository_->getInitialMembers(); } bool Conversation::isInitialMember(const std::string& uri) const { auto members = getInitialMembers(); return std::find(members.begin(), members.end(), uri) != members.end(); } void Conversation::updateInfos(const std::map<std::string, std::string>& map, const OnDoneCb& cb) { dht::ThreadPool::io().run([w = weak(), map = std::move(map), cb = std::move(cb)] { if (auto sthis = w.lock()) { auto& repo = sthis->pimpl_->repository_; std::unique_lock lk(sthis->pimpl_->writeMtx_); auto commit = repo->updateInfos(map); sthis->pimpl_->announce(commit, true); lk.unlock(); if (cb) cb(!commit.empty(), commit); emitSignal<libjami::ConversationSignal::ConversationProfileUpdated>( sthis->pimpl_->accountId_, repo->id(), repo->infos()); } }); } std::map<std::string, std::string> Conversation::infos() const { return pimpl_->repository_->infos(); } void Conversation::updatePreferences(const std::map<std::string, std::string>& map) { auto filePath = pimpl_->conversationDataPath_ / "preferences"; auto prefs = map; auto itLast = prefs.find(LAST_MODIFIED); if (itLast != prefs.end()) { if (std::filesystem::is_regular_file(filePath)) { auto lastModified = fileutils::lastWriteTimeInSeconds(filePath); try { if (lastModified >= std::stoul(itLast->second)) return; } catch (...) { return; } } prefs.erase(itLast); } std::ofstream file(filePath, std::ios::trunc | std::ios::binary); msgpack::pack(file, prefs); emitSignal<libjami::ConversationSignal::ConversationPreferencesUpdated>(pimpl_->accountId_, id(), std::move(prefs)); } std::map<std::string, std::string> Conversation::preferences(bool includeLastModified) const { try { std::map<std::string, std::string> preferences; auto filePath = pimpl_->conversationDataPath_ / "preferences"; auto file = fileutils::loadFile(filePath); msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); oh.get().convert(preferences); if (includeLastModified) preferences[LAST_MODIFIED] = std::to_string(fileutils::lastWriteTimeInSeconds(filePath)); return preferences; } catch (const std::exception& e) { } return {}; } std::vector<uint8_t> Conversation::vCard() const { try { return fileutils::loadFile(pimpl_->repoPath() / "profile.vcf"); } catch (...) { } return {}; } std::shared_ptr<TransferManager> Conversation::dataTransfer() const { return pimpl_->transferManager_; } bool Conversation::onFileChannelRequest(const std::string& member, const std::string& fileId, bool verifyShaSum) const { if (!isMember(member)) return false; auto sep = fileId.find('_'); if (sep == std::string::npos) return false; auto interactionId = fileId.substr(0, sep); auto commit = getCommit(interactionId); if (commit == std::nullopt || commit->find("type") == commit->end() || commit->find("tid") == commit->end() || commit->find("sha3sum") == commit->end() || commit->at("type") != "application/data-transfer+json") { JAMI_WARNING("[Account {:s}] {} requested invalid file transfer commit {}", pimpl_->accountId_, member, interactionId); return false; } auto path = dataTransfer()->path(fileId); if (!std::filesystem::is_regular_file(path)) { // Check if dangling symlink if (std::filesystem::is_symlink(path)) { dhtnet::fileutils::remove(path, true); } JAMI_WARNING("[Account {:s}] {:s} asked for non existing file {} in {:s}", pimpl_->accountId_, member, fileId, id()); return false; } // Check that our file is correct before sending if (verifyShaSum && commit->at("sha3sum") != fileutils::sha3File(path)) { JAMI_WARNING( "[Account {:s}] {:s} asked for file {:s} in {:s}, but our version is not complete or corrupted", pimpl_->accountId_, member, fileId, id()); return false; } return true; } bool Conversation::downloadFile(const std::string& interactionId, const std::string& fileId, const std::string& path, const std::string&, const std::string& deviceId, std::size_t start, std::size_t end) { auto commit = getCommit(interactionId); if (commit == std::nullopt || commit->at("type") != "application/data-transfer+json") { JAMI_ERROR("Commit doesn't exists or is not a file transfer {} (Conversation: {}) ", interactionId, id()); return false; } auto tid = commit->find("tid"); auto sha3sum = commit->find("sha3sum"); auto size_str = commit->find("totalSize"); if (tid == commit->end() || sha3sum == commit->end() || size_str == commit->end()) { JAMI_ERROR("Invalid file transfer commit (missing tid, size or sha3)"); return false; } auto totalSize = to_int<ssize_t>(size_str->second, (ssize_t) -1); if (totalSize < 0) { JAMI_ERROR("Invalid file size {}", totalSize); return false; } // Be sure to not lock conversation dht::ThreadPool().io().run([w = weak(), deviceId, fileId, interactionId, sha3sum = sha3sum->second, path, totalSize, start, end] { if (auto shared = w.lock()) { auto acc = shared->pimpl_->account_.lock(); if (!acc) return; shared->dataTransfer()->waitForTransfer(fileId, interactionId, sha3sum, path, totalSize); acc->askForFileChannel(shared->id(), deviceId, interactionId, fileId, start, end); } }); return true; } void Conversation::hasFetched(const std::string& deviceId, const std::string& commitId) { dht::ThreadPool::io().run([w = weak(), deviceId, commitId]() { auto sthis = w.lock(); if (!sthis) return; // Update fetched for Uri auto uri = sthis->uriFromDevice(deviceId); if (uri.empty() || uri == sthis->pimpl_->userId_) return; // When a user fetches a commit, the message is sent for this person sthis->pimpl_->updateStatus(uri, libjami::Account::MessageStates::SENT, commitId, std::to_string(std::time(nullptr)), true); }); } void Conversation::Impl::updateStatus(const std::string& uri, libjami::Account::MessageStates st, const std::string& commitId, const std::string& ts, bool emit) { // This method can be called if peer send us a status or if another device sync. Emit will be true if a peer send us a status and will emit to other connected devices. LogOptions options; std::map<std::string, std::map<std::string, std::string>> newStatus; { // Update internal structures. std::lock_guard lk(messageStatusMtx_); auto& status = messagesStatus_[uri]; auto& oldStatus = status[st == libjami::Account::MessageStates::SENT ? "fetched" : "read"]; if (oldStatus == commitId) return; // Nothing to do options.to = oldStatus; options.from = commitId; oldStatus = commitId; status[st == libjami::Account::MessageStates::SENT ? "fetched_ts" : "read_ts"] = ts; saveStatus(); if (emit) newStatus[uri].insert(status.begin(), status.end()); } if (emit && messageStatusCb_) { messageStatusCb_(newStatus); } // Update messages status for all commit between the old and new one options.logIfNotFound = false; options.fastLog = true; History optHistory; std::lock_guard lk(historyMtx_); // Avoid to announce messages while updating status. auto res = loadMessages2(options, &optHistory); if (res.size() == 0) { // In this case, commit is not received yet, so we cache it futureStatus[commitId][uri] = static_cast<int32_t>(st); } for (const auto& [cid, _]: optHistory.quickAccess) { auto message = loadedHistory_.quickAccess.find(cid); if (message != loadedHistory_.quickAccess.end()) { // Update message and emit to client, if(static_cast<int32_t>(st) > message->second->status[uri]){ message->second->status[uri] = static_cast<int32_t>(st); emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>( accountId_, repository_->id(), uri, cid, static_cast<int>(st)); } } else { // In this case, commit is not loaded by client, so we cache it // No need to emit to client, they will get a correct status on load. futureStatus[cid][uri] = static_cast<int32_t>(st); } } } bool Conversation::setMessageDisplayed(const std::string& uri, const std::string& interactionId) { std::lock_guard lk(pimpl_->messageStatusMtx_); if (pimpl_->messagesStatus_[uri]["read"] == interactionId) return false; // Nothing to do dht::ThreadPool::io().run([w = weak(), uri, interactionId]() { auto sthis = w.lock(); if (!sthis) return; sthis->pimpl_->updateStatus(uri, libjami::Account::MessageStates::DISPLAYED, interactionId, std::to_string(std::time(nullptr)), true); }); return true; } std::map<std::string, std::map<std::string, std::string>> Conversation::messageStatus() const { std::lock_guard lk(pimpl_->messageStatusMtx_); return pimpl_->messagesStatus_; } void Conversation::updateMessageStatus(const std::map<std::string, std::map<std::string, std::string>>& messageStatus) { std::unique_lock lk(pimpl_->messageStatusMtx_); std::vector<std::tuple<libjami::Account::MessageStates, std::string, std::string, std::string>> stVec; for (const auto& [uri, status] : messageStatus) { auto& oldMs = pimpl_->messagesStatus_[uri]; if (status.find("fetched_ts") != status.end() && status.at("fetched") != oldMs["fetched"]) { if (oldMs["fetched_ts"].empty() || std::stol(oldMs["fetched_ts"]) <= std::stol(status.at("fetched_ts"))) { stVec.emplace_back(libjami::Account::MessageStates::SENT, uri, status.at("fetched"), status.at("fetched_ts")); } } if (status.find("read_ts") != status.end() && status.at("read") != oldMs["read"]) { if (oldMs["read_ts"].empty() || std::stol(oldMs["read_ts"]) <= std::stol(status.at("read_ts"))) { stVec.emplace_back(libjami::Account::MessageStates::DISPLAYED, uri, status.at("read"), status.at("read_ts")); } } } lk.unlock(); for (const auto& [status, uri, commitId, ts] : stVec) { pimpl_->updateStatus(uri, status, commitId, ts); } } void Conversation::onMessageStatusChanged(const std::function<void(const std::map<std::string, std::map<std::string, std::string>>&)>& cb) { std::unique_lock lk(pimpl_->messageStatusMtx_); pimpl_->messageStatusCb_ = cb; } #ifdef LIBJAMI_TESTABLE void Conversation::onBootstrapStatus(const std::function<void(std::string, BootstrapStatus)>& cb) { pimpl_->bootstrapCbTest_ = cb; } #endif void Conversation::checkBootstrapMember(const asio::error_code& ec, std::vector<std::map<std::string, std::string>> members) { if (ec == asio::error::operation_aborted) return; auto acc = pimpl_->account_.lock(); if (pimpl_->swarmManager_->getRoutingTable().getNodes().size() > 0 or not acc) return; // We bootstrap the DRT with devices who already wrote in the repository. // However, in a conversation, a large number of devices may just watch // the conversation, but never write any message. std::unique_lock lock(pimpl_->membersMtx_); std::string uri; while (!members.empty()) { auto member = std::move(members.back()); members.pop_back(); uri = std::move(member.at("uri")); if (uri != pimpl_->userId_ && pimpl_->checkedMembers_.find(uri) == pimpl_->checkedMembers_.end()) break; } auto fallbackFailed = [](auto sthis) { JAMI_WARNING("{}[SwarmManager {}] Bootstrap: Fallback failed. Wait for remote connections.", sthis->pimpl_->toString(), fmt::ptr(sthis->pimpl_->swarmManager_.get())); #ifdef LIBJAMI_TESTABLE if (sthis->pimpl_->bootstrapCbTest_) sthis->pimpl_->bootstrapCbTest_(sthis->id(), BootstrapStatus::FAILED); #endif }; // If members is empty, we finished the fallback un-successfully if (members.empty() && uri.empty()) { lock.unlock(); fallbackFailed(this); return; } // Fallback, check devices of a member (we didn't check yet) in the conversation pimpl_->checkedMembers_.emplace(uri); auto devices = std::make_shared<std::vector<NodeId>>(); acc->forEachDevice( dht::InfoHash(uri), [w = weak(), devices](const std::shared_ptr<dht::crypto::PublicKey>& dev) { // Test if already sent if (auto sthis = w.lock()) { if (!sthis->pimpl_->swarmManager_->getRoutingTable().hasKnownNode(dev->getLongId())) devices->emplace_back(dev->getLongId()); } }, [w = weak(), devices, members = std::move(members), uri, fallbackFailed=std::move(fallbackFailed)](bool ok) { auto sthis = w.lock(); if (!sthis) return; auto checkNext = true; if (ok && devices->size() != 0) { #ifdef LIBJAMI_TESTABLE if (sthis->pimpl_->bootstrapCbTest_) sthis->pimpl_->bootstrapCbTest_(sthis->id(), BootstrapStatus::FALLBACK); #endif JAMI_WARNING("{}[SwarmManager {}] Bootstrap: Fallback with member: {}", sthis->pimpl_->toString(), fmt::ptr(sthis->pimpl_->swarmManager_), uri); if (sthis->pimpl_->swarmManager_->setKnownNodes(*devices)) checkNext = false; } if (checkNext) { // Check next member sthis->pimpl_->fallbackTimer_->expires_at(std::chrono::steady_clock::now()); sthis->pimpl_->fallbackTimer_->async_wait( std::bind(&Conversation::checkBootstrapMember, sthis, std::placeholders::_1, std::move(members))); } else { // In this case, all members are checked. Fallback failed fallbackFailed(sthis); } }); } void Conversation::bootstrap(std::function<void()> onBootstraped, const std::vector<DeviceId>& knownDevices) { if (!pimpl_ || !pimpl_->repository_ || !pimpl_->swarmManager_) return; // Here, we bootstrap the DRT with devices who already wrote in the conversation // If this doesn't work, it will try to fallback with checkBootstrapMember // If it works, the callback onConnectionChanged will be called with ok=true pimpl_->bootstrapCb_ = std::move(onBootstraped); std::vector<DeviceId> devices = knownDevices; for (const auto& [member, memberDevices] : pimpl_->repository_->devices()) { if (!isBanned(member)) devices.insert(devices.end(), memberDevices.begin(), memberDevices.end()); } JAMI_DEBUG("{}[SwarmManager {}] Bootstrap with {} devices", pimpl_->toString(), fmt::ptr(pimpl_->swarmManager_), devices.size()); // set callback auto fallback = [](auto sthis, bool now = false) { // Fallback auto acc = sthis->pimpl_->account_.lock(); if (!acc) return; auto members = sthis->getMembers(false, false); std::shuffle(members.begin(), members.end(), acc->rand); if (now) { sthis->pimpl_->fallbackTimer_->expires_at(std::chrono::steady_clock::now()); } else { auto timeForBootstrap = std::min(static_cast<size_t>(8), members.size()); sthis->pimpl_->fallbackTimer_->expires_at(std::chrono::steady_clock::now() + 20s - std::chrono::seconds(timeForBootstrap)); JAMI_DEBUG("{}[SwarmManager {}] Fallback in {} seconds", sthis->pimpl_->toString(), fmt::ptr(sthis->pimpl_->swarmManager_.get()), (20 - timeForBootstrap)); } sthis->pimpl_->fallbackTimer_->async_wait(std::bind(&Conversation::checkBootstrapMember, sthis, std::placeholders::_1, std::move(members))); }; pimpl_->swarmManager_->onConnectionChanged([w = weak(), fallback](bool ok) { // This will call methods from accounts, so trigger on another thread. dht::ThreadPool::io().run([w, ok, fallback=std::move(fallback)] { auto sthis = w.lock(); if (!sthis) return; if (ok) { // Bootstrap succeeded! { std::lock_guard lock(sthis->pimpl_->membersMtx_); sthis->pimpl_->checkedMembers_.clear(); } if (sthis->pimpl_->bootstrapCb_) sthis->pimpl_->bootstrapCb_(); #ifdef LIBJAMI_TESTABLE if (sthis->pimpl_->bootstrapCbTest_) sthis->pimpl_->bootstrapCbTest_(sthis->id(), BootstrapStatus::SUCCESS); #endif return; } fallback(sthis); }); }); { std::lock_guard lock(pimpl_->membersMtx_); pimpl_->checkedMembers_.clear(); } // If is shutdown, the conversation was re-added, causing no new nodes to be connected, but just a classic connectivity change if (pimpl_->swarmManager_->isShutdown()) { pimpl_->swarmManager_->restart(); pimpl_->swarmManager_->maintainBuckets(); } else if (!pimpl_->swarmManager_->setKnownNodes(devices)) { fallback(this, true); } } std::vector<std::string> Conversation::commitsEndedCalls() { pimpl_->loadActiveCalls(); pimpl_->loadHostedCalls(); auto commits = pimpl_->commitsEndedCalls(); if (!commits.empty()) { // Announce to client dht::ThreadPool::io().run([w = weak(), commits] { if (auto sthis = w.lock()) sthis->pimpl_->announce(commits, true); }); } return commits; } void Conversation::onMembersChanged(OnMembersChanged&& cb) { pimpl_->onMembersChanged_ = std::move(cb); pimpl_->repository_->onMembersChanged([w=weak()] (const std::set<std::string>& memberUris) { if (auto sthis = w.lock()) sthis->pimpl_->onMembersChanged_(memberUris); }); } void Conversation::onNeedSocket(NeedSocketCb needSocket) { pimpl_->swarmManager_->needSocketCb_ = [needSocket = std::move(needSocket), w=weak()](const std::string& deviceId, ChannelCb&& cb) { if (auto sthis = w.lock()) needSocket(sthis->id(), deviceId, std::move(cb), "application/im-gitmessage-id"); }; } void Conversation::addSwarmChannel(std::shared_ptr<dhtnet::ChannelSocket> channel) { auto deviceId = channel->deviceId(); // Transmit avatar if necessary // We do this here, because at this point we know both sides are connected and in // the same conversation // addSwarmChannel is a bit more complex, but it should be the best moment to do this. auto cert = channel->peerCertificate(); if (!cert || !cert->issuer) return; auto member = cert->issuer->getId().toString(); pimpl_->swarmManager_->addChannel(std::move(channel)); dht::ThreadPool::io().run([member, deviceId, a = pimpl_->account_, w = weak_from_this()] { auto sthis = w.lock(); if (auto account = a.lock()) { account->sendProfile(sthis->id(), member, deviceId.toString()); } }); } uint32_t Conversation::countInteractions(const std::string& toId, const std::string& fromId, const std::string& authorUri) const { LogOptions options; options.to = toId; options.from = fromId; options.authorUri = authorUri; options.logIfNotFound = false; options.fastLog = true; History history; auto res = pimpl_->loadMessages2(options, &history); return res.size(); } void Conversation::search(uint32_t req, const Filter& filter, const std::shared_ptr<std::atomic_int>& flag) const { // Because logging a conversation can take quite some time, // do it asynchronously dht::ThreadPool::io().run([w = weak(), req, filter, flag] { if (auto sthis = w.lock()) { History history; std::vector<std::map<std::string, std::string>> commits {}; // std::regex_constants::ECMAScript is the default flag. auto re = std::regex(filter.regexSearch, filter.caseSensitive ? std::regex_constants::ECMAScript : std::regex_constants::icase); sthis->pimpl_->repository_->log( [&](const auto& id, const auto& author, auto& commit) { if (!filter.author.empty() && filter.author != sthis->uriFromDevice(author.email)) { // Filter author return CallbackResult::Skip; } auto commitTime = git_commit_time(commit.get()); if (filter.before && filter.before < commitTime) { // Only get commits before this date return CallbackResult::Skip; } if (filter.after && filter.after > commitTime) { // Only get commits before this date if (git_commit_parentcount(commit.get()) <= 1) return CallbackResult::Break; else return CallbackResult::Skip; // Because we are sorting it with // GIT_SORT_TOPOLOGICAL | GIT_SORT_TIME } return CallbackResult::Ok; // Continue }, [&](auto&& cc) { if (auto optMessage = sthis->pimpl_->repository_->convCommitToMap(cc)) sthis->pimpl_->addToHistory({optMessage.value()}, false, false, &history); }, [&](auto id, auto, auto) { if (id == filter.lastId) return true; return false; }, "", false); // Search on generated history for (auto& message : history.messageList) { auto contentType = message->type; auto isSearchable = contentType == "text/plain" || contentType == "application/data-transfer+json"; if (filter.type.empty() && !isSearchable) { // Not searchable, at least for now continue; } else if (contentType == filter.type || filter.type.empty()) { if (isSearchable) { // If it's a text match the body, else the display name auto body = contentType == "text/plain" ? message->body.at("body") : message->body.at("displayName"); std::smatch body_match; if (std::regex_search(body, body_match, re)) { auto commit = message->body; commit["id"] = message->id; commit["type"] = message->type; commits.emplace_back(commit); } } else { // Matching type, just add it to the results commits.emplace_back(message->body); } if (filter.maxResult != 0 && commits.size() == filter.maxResult) break; } } if (commits.size() > 0) emitSignal<libjami::ConversationSignal::MessagesFound>(req, sthis->pimpl_->accountId_, sthis->id(), std::move(commits)); // If we're the latest thread, inform client that the search is finished if ((*flag)-- == 1 /* decrement return the old value */) { emitSignal<libjami::ConversationSignal::MessagesFound>( req, sthis->pimpl_->accountId_, std::string {}, std::vector<std::map<std::string, std::string>> {}); } } }); } void Conversation::hostConference(Json::Value&& message, OnDoneCb&& cb) { if (!message.isMember("confId")) { JAMI_ERR() << "Malformed commit"; return; } auto now = std::chrono::system_clock::now(); auto nowSecs = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count(); { std::lock_guard lk(pimpl_->activeCallsMtx_); pimpl_->hostedCalls_[message["confId"].asString()] = nowSecs; pimpl_->saveHostedCalls(); } sendMessage(std::move(message), "", {}, std::move(cb)); } bool Conversation::isHosting(const std::string& confId) const { auto info = infos(); if (info["rdvDevice"] == pimpl_->deviceId_ && info["rdvHost"] == pimpl_->userId_) return true; // We are the current device Host std::lock_guard lk(pimpl_->activeCallsMtx_); return pimpl_->hostedCalls_.find(confId) != pimpl_->hostedCalls_.end(); } void Conversation::removeActiveConference(Json::Value&& message, OnDoneCb&& cb) { if (!message.isMember("confId")) { JAMI_ERR() << "Malformed commit"; return; } auto erased = false; { std::lock_guard lk(pimpl_->activeCallsMtx_); erased = pimpl_->hostedCalls_.erase(message["confId"].asString()); } if (erased) { pimpl_->saveHostedCalls(); sendMessage(std::move(message), "", {}, std::move(cb)); } else cb(false, ""); } std::vector<std::map<std::string, std::string>> Conversation::currentCalls() const { std::lock_guard lk(pimpl_->activeCallsMtx_); return pimpl_->activeCalls_; } } // namespace jami
108,874
C++
.cpp
2,521
31.318921
171
0.551752
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,792
transfer_channel_handler.cpp
savoirfairelinux_jami-daemon/src/jamidht/transfer_channel_handler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "jamidht/transfer_channel_handler.h" #include <charconv> #include "fileutils.h" namespace jami { TransferChannelHandler::TransferChannelHandler(const std::shared_ptr<JamiAccount>& account, dhtnet::ConnectionManager& cm) : ChannelHandlerInterface() , account_(account) , connectionManager_(cm) { if (auto acc = account_.lock()) idPath_ = fileutils::get_data_dir() / acc->getAccountID(); } TransferChannelHandler::~TransferChannelHandler() {} void TransferChannelHandler::connect(const DeviceId& deviceId, const std::string& channelName, ConnectCb&& cb) {} bool TransferChannelHandler::onRequest(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& name) { auto acc = account_.lock(); if (!acc || !cert || !cert->issuer) return false; auto cm = acc->convModule(true); if (!cm) return false; auto uri = cert->issuer->getId().toString(); // Else, check if it's a profile or file in a conversation. auto idstr = std::string_view(name).substr(DATA_TRANSFER_SCHEME.size()); // Remove arguments for now auto sep = idstr.find_last_of('?'); idstr = idstr.substr(0, sep); if (idstr == "profile.vcf") { // If it's our profile from another device return uri == acc->getUsername(); } sep = idstr.find('/'); auto lastSep = idstr.find_last_of('/'); auto conversationId = std::string(idstr.substr(0, sep)); auto fileHost = idstr.substr(sep + 1, lastSep - sep - 1); auto fileId = idstr.substr(lastSep + 1); if (fileHost == acc->currentDeviceId()) return false; // Check if peer is member of the conversation if (fileId == fmt::format("{}.vcf", acc->getUsername()) || fileId == "profile.vcf") { // Or a member from the conversation auto members = cm->getConversationMembers(conversationId); return std::find_if(members.begin(), members.end(), [&](auto m) { return m["uri"] == uri; }) != members.end(); } else if (fileHost == "profile") { // If a profile is sent, check if it's from another device return uri == acc->getUsername(); } return cm->onFileChannelRequest(conversationId, uri, std::string(fileId), acc->sha3SumVerify()); } void TransferChannelHandler::onReady(const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) { auto acc = account_.lock(); if (!acc) return; // Remove scheme auto idstr = name.substr(DATA_TRANSFER_SCHEME.size()); // Parse arguments auto sep = idstr.find_last_of('?'); std::string arguments; if (sep != std::string::npos) { arguments = idstr.substr(sep + 1); idstr = idstr.substr(0, sep); } auto start = 0u, end = 0u; uint64_t lastModified = 0; std::string sha3Sum; for (const auto arg : split_string(arguments, '&')) { auto keyVal = split_string(arg, '='); if (keyVal.size() == 2) { if (keyVal[0] == "start") { start = to_int<unsigned>(keyVal[1]); } else if (keyVal[0] == "end") { end = to_int<unsigned>(keyVal[1]); } else if (keyVal[0] == "sha3") { sha3Sum = keyVal[1]; } else if (keyVal[0] == "modified") { try { lastModified = jami::to_int<uint64_t>(keyVal[1]); } catch (const std::exception& e) { JAMI_WARNING("TransferChannel: Unable to parse modified date: {}: {}", keyVal[1], e.what()); } } } } // Check if profile if (idstr == "profile.vcf") { if (!channel->isInitiator()) { // Only accept newest profiles if (lastModified == 0 || lastModified > fileutils::lastWriteTimeInSeconds(acc->profilePath())) acc->dataTransfer()->onIncomingProfile(channel, sha3Sum); else channel->shutdown(); } else { // If it's a profile from sync auto path = idPath_ / "profile.vcf"; acc->dataTransfer()->transferFile(channel, idstr, "", path.string()); } return; } auto splitted_id = split_string(idstr, '/'); if (splitted_id.size() < 3) { JAMI_ERR() << "Unsupported ID detected " << name; channel->shutdown(); return; } // convId/fileHost/fileId or convId/profile/fileId auto conversationId = std::string(splitted_id[0]); auto fileHost = std::string(splitted_id[1]); auto isContactProfile = splitted_id[1] == "profile"; auto fileId = std::string(splitted_id[splitted_id.size() - 1]); if (channel->isInitiator()) return; // Profile for a member in the conversation if (fileId == fmt::format("{}.vcf", acc->getUsername())) { auto path = idPath_ / "profile.vcf"; acc->dataTransfer()->transferFile(channel, fileId, "", path.string()); return; } else if (isContactProfile && fileId.find(".vcf") != std::string::npos) { auto path = acc->dataTransfer()->profilePath(fileId.substr(0, fileId.size() - 4)); acc->dataTransfer()->transferFile(channel, fileId, "", path.string()); return; } else if (fileId == "profile.vcf") { acc->dataTransfer()->onIncomingProfile(channel, sha3Sum); return; } // Check if it's a file in a conversation auto dt = acc->dataTransfer(conversationId); sep = fileId.find('_'); if (!dt or sep == std::string::npos) { channel->shutdown(); return; } auto interactionId = fileId.substr(0, sep); auto path = dt->path(fileId); dt->transferFile(channel, fileId, interactionId, path.string(), start, end); } } // namespace jami
6,938
C++
.cpp
170
32.152941
100
0.584358
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,793
archive_account_manager.cpp
savoirfairelinux_jami-daemon/src/jamidht/archive_account_manager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "archive_account_manager.h" #include "accountarchive.h" #include "fileutils.h" #include "libdevcrypto/Common.h" #include "archiver.h" #include "base64.h" #include "jami/account_const.h" #include "account_schema.h" #include "jamidht/conversation_module.h" #include "manager.h" #include <opendht/dhtrunner.h> #include <opendht/thread_pool.h> #include <memory> #include <fstream> namespace jami { const constexpr auto EXPORT_KEY_RENEWAL_TIME = std::chrono::minutes(20); void ArchiveAccountManager::initAuthentication(const std::string& accountId, PrivateKey key, std::string deviceName, std::unique_ptr<AccountCredentials> credentials, AuthSuccessCallback onSuccess, AuthFailureCallback onFailure, const OnChangeCallback& onChange) { auto ctx = std::make_shared<AuthContext>(); ctx->accountId = accountId; ctx->key = key; ctx->request = buildRequest(key); ctx->deviceName = std::move(deviceName); ctx->credentials = dynamic_unique_cast<ArchiveAccountCredentials>(std::move(credentials)); ctx->onSuccess = std::move(onSuccess); ctx->onFailure = std::move(onFailure); if (not ctx->credentials) { ctx->onFailure(AuthError::INVALID_ARGUMENTS, "invalid credentials"); return; } onChange_ = std::move(onChange); if (ctx->credentials->scheme == "dht") { loadFromDHT(ctx); return; } dht::ThreadPool::computation().run([ctx = std::move(ctx), w = weak_from_this()] { auto this_ = std::static_pointer_cast<ArchiveAccountManager>(w.lock()); if (not this_) return; try { if (ctx->credentials->scheme == "file") { // Import from external archive this_->loadFromFile(*ctx); } else { // Create/migrate local account bool hasArchive = not ctx->credentials->uri.empty() and std::filesystem::is_regular_file(ctx->credentials->uri); if (hasArchive) { // Create/migrate from local archive if (ctx->credentials->updateIdentity.first and ctx->credentials->updateIdentity.second and needsMigration(ctx->credentials->updateIdentity)) { this_->migrateAccount(*ctx); } else { this_->loadFromFile(*ctx); } } else if (ctx->credentials->updateIdentity.first and ctx->credentials->updateIdentity.second) { auto future_keypair = dht::ThreadPool::computation().get<dev::KeyPair>( &dev::KeyPair::create); AccountArchive a; JAMI_WARN("[Auth] Converting certificate from old account %s", ctx->credentials->updateIdentity.first->getPublicKey() .getId() .toString() .c_str()); a.id = std::move(ctx->credentials->updateIdentity); try { a.ca_key = std::make_shared<dht::crypto::PrivateKey>( fileutils::loadFile("ca.key", this_->path_)); } catch (...) { } this_->updateCertificates(a, ctx->credentials->updateIdentity); a.eth_key = future_keypair.get().secret().makeInsecure().asBytes(); this_->onArchiveLoaded(*ctx, std::move(a)); } else { this_->createAccount(*ctx); } } } catch (const std::exception& e) { ctx->onFailure(AuthError::UNKNOWN, e.what()); } }); } bool ArchiveAccountManager::updateCertificates(AccountArchive& archive, dht::crypto::Identity& device) { JAMI_WARN("Updating certificates"); using Certificate = dht::crypto::Certificate; // We need the CA key to resign certificates if (not archive.id.first or not *archive.id.first or not archive.id.second or not archive.ca_key or not *archive.ca_key) return false; // Currently set the CA flag and update expiration dates bool updated = false; auto& cert = archive.id.second; auto ca = cert->issuer; // Update CA if possible and relevant if (not ca or (not ca->issuer and (not ca->isCA() or ca->getExpiration() < clock::now()))) { ca = std::make_shared<Certificate>( Certificate::generate(*archive.ca_key, "Jami CA", {}, true)); updated = true; JAMI_DBG("CA CRT re-generated"); } // Update certificate if (updated or not cert->isCA() or cert->getExpiration() < clock::now()) { cert = std::make_shared<Certificate>( Certificate::generate(*archive.id.first, "Jami", dht::crypto::Identity {archive.ca_key, ca}, true)); updated = true; JAMI_DBG("Jami CRT re-generated"); } if (updated and device.first and *device.first) { // update device certificate device.second = std::make_shared<Certificate>( Certificate::generate(*device.first, "Jami device", archive.id)); JAMI_DBG("device CRT re-generated"); } return updated; } bool ArchiveAccountManager::setValidity(std::string_view scheme, const std::string& password, dht::crypto::Identity& device, const dht::InfoHash& id, int64_t validity) { auto archive = readArchive(scheme, password); // We need the CA key to resign certificates if (not archive.id.first or not *archive.id.first or not archive.id.second or not archive.ca_key or not *archive.ca_key) return false; auto updated = false; if (id) JAMI_WARN("Updating validity for certificate with id: %s", id.to_c_str()); else JAMI_WARN("Updating validity for certificates"); auto& cert = archive.id.second; auto ca = cert->issuer; if (not ca) return false; // using Certificate = dht::crypto::Certificate; // Update CA if possible and relevant if (not id or ca->getId() == id) { ca->setValidity(*archive.ca_key, validity); updated = true; JAMI_DBG("CA CRT re-generated"); } // Update certificate if (updated or not id or cert->getId() == id) { cert->setValidity(dht::crypto::Identity {archive.ca_key, ca}, validity); device.second->issuer = cert; updated = true; JAMI_DBG("Jami CRT re-generated"); } if (updated) { archive.save(fileutils::getFullPath(path_, archivePath_), scheme, password); } if (updated or not id or device.second->getId() == id) { // update device certificate device.second->setValidity(archive.id, validity); updated = true; } return updated; } void ArchiveAccountManager::createAccount(AuthContext& ctx) { AccountArchive a; auto ca = dht::crypto::generateIdentity("Jami CA"); if (!ca.first || !ca.second) { throw std::runtime_error("Unable to generate CA for this account."); } a.id = dht::crypto::generateIdentity("Jami", ca, 4096, true); if (!a.id.first || !a.id.second) { throw std::runtime_error("Unable to generate identity for this account."); } JAMI_WARN("[Auth] New account: CA: %s, ID: %s", ca.second->getId().toString().c_str(), a.id.second->getId().toString().c_str()); a.ca_key = ca.first; auto keypair = dev::KeyPair::create(); a.eth_key = keypair.secret().makeInsecure().asBytes(); onArchiveLoaded(ctx, std::move(a)); } void ArchiveAccountManager::loadFromFile(AuthContext& ctx) { JAMI_WARN("[Auth] Loading archive from: %s", ctx.credentials->uri.c_str()); AccountArchive archive; try { archive = AccountArchive(ctx.credentials->uri, ctx.credentials->password_scheme, ctx.credentials->password); } catch (const std::exception& ex) { JAMI_WARN("[Auth] Unable to read file: %s", ex.what()); ctx.onFailure(AuthError::INVALID_ARGUMENTS, ex.what()); return; } onArchiveLoaded(ctx, std::move(archive)); } struct ArchiveAccountManager::DhtLoadContext { dht::DhtRunner dht; std::pair<bool, bool> stateOld {false, true}; std::pair<bool, bool> stateNew {false, true}; bool found {false}; }; void ArchiveAccountManager::loadFromDHT(const std::shared_ptr<AuthContext>& ctx) { ctx->dhtContext = std::make_unique<DhtLoadContext>(); ctx->dhtContext->dht.run(ctx->credentials->dhtPort, {}, true); for (const auto& bootstrap : ctx->credentials->dhtBootstrap) ctx->dhtContext->dht.bootstrap(bootstrap); auto searchEnded = [ctx]() { if (not ctx->dhtContext or ctx->dhtContext->found) { return; } auto& s = *ctx->dhtContext; if (s.stateOld.first && s.stateNew.first) { dht::ThreadPool::computation().run( [ctx, network_error = !s.stateOld.second && !s.stateNew.second] { ctx->dhtContext.reset(); JAMI_WARN("[Auth] Failure looking for archive on DHT: %s", /**/ network_error ? "network error" : "not found"); ctx->onFailure(network_error ? AuthError::NETWORK : AuthError::UNKNOWN, ""); }); } }; auto search = [ctx, searchEnded, w=weak_from_this()](bool previous) { std::vector<uint8_t> key; dht::InfoHash loc; auto& s = previous ? ctx->dhtContext->stateOld : ctx->dhtContext->stateNew; // compute archive location and decryption keys try { std::tie(key, loc) = computeKeys(ctx->credentials->password, ctx->credentials->uri, previous); JAMI_DBG("[Auth] Attempting to load account from DHT with %s at %s", /**/ ctx->credentials->uri.c_str(), loc.toString().c_str()); if (not ctx->dhtContext or ctx->dhtContext->found) { return; } ctx->dhtContext->dht.get( loc, [ctx, key = std::move(key), w](const std::shared_ptr<dht::Value>& val) { std::vector<uint8_t> decrypted; try { decrypted = archiver::decompress(dht::crypto::aesDecrypt(val->data, key)); } catch (const std::exception& ex) { return true; } JAMI_DBG("[Auth] Found archive on the DHT"); ctx->dhtContext->found = true; dht::ThreadPool::computation().run([ctx, decrypted = std::move(decrypted), w] { try { auto archive = AccountArchive(decrypted); if (auto sthis = std::static_pointer_cast<ArchiveAccountManager>(w.lock())) { if (ctx->dhtContext) { ctx->dhtContext->dht.join(); ctx->dhtContext.reset(); } sthis->onArchiveLoaded(*ctx, std::move(archive) /*, std::move(contacts)*/); } } catch (const std::exception& e) { ctx->onFailure(AuthError::UNKNOWN, ""); } }); return not ctx->dhtContext->found; }, [=, &s](bool ok) { JAMI_DBG("[Auth] DHT archive search ended at %s", /**/ loc.toString().c_str()); s.first = true; s.second = ok; searchEnded(); }); } catch (const std::exception& e) { // JAMI_ERR("Error computing kedht::ThreadPool::computation().run(ys: %s", e.what()); s.first = true; s.second = true; searchEnded(); return; } }; dht::ThreadPool::computation().run(std::bind(search, true)); dht::ThreadPool::computation().run(std::bind(search, false)); } void ArchiveAccountManager::migrateAccount(AuthContext& ctx) { JAMI_WARN("[Auth] Account migration needed"); AccountArchive archive; try { archive = readArchive(ctx.credentials->password_scheme, ctx.credentials->password); } catch (...) { JAMI_DBG("[Auth] Unable to load archive"); ctx.onFailure(AuthError::INVALID_ARGUMENTS, ""); return; } updateArchive(archive); if (updateCertificates(archive, ctx.credentials->updateIdentity)) { // because updateCertificates already regenerate a device, we do not need to // regenerate one in onArchiveLoaded onArchiveLoaded(ctx, std::move(archive)); } else ctx.onFailure(AuthError::UNKNOWN, ""); } void ArchiveAccountManager::onArchiveLoaded(AuthContext& ctx, AccountArchive&& a) { auto ethAccount = dev::KeyPair(dev::Secret(a.eth_key)).address().hex(); dhtnet::fileutils::check_dir(path_, 0700); a.save(fileutils::getFullPath(path_, archivePath_), ctx.credentials ? ctx.credentials->password_scheme : "", ctx.credentials ? ctx.credentials->password : ""); if (not a.id.second->isCA()) { JAMI_ERR("[Auth] Attempting to sign a certificate with a non-CA."); } std::shared_ptr<dht::crypto::Certificate> deviceCertificate; std::unique_ptr<ContactList> contacts; auto usePreviousIdentity = false; // If updateIdentity got a valid certificate, there is no need for a new cert if (auto oldId = ctx.credentials->updateIdentity.second) { contacts = std::make_unique<ContactList>(ctx.accountId, oldId, path_, onChange_); if (contacts->isValidAccountDevice(*oldId) && ctx.credentials->updateIdentity.first) { deviceCertificate = oldId; usePreviousIdentity = true; JAMI_WARN("[Auth] Using previously generated certificate %s", deviceCertificate->getLongId().toString().c_str()); } else { contacts.reset(); } } // Generate a new device if needed if (!deviceCertificate) { JAMI_WARN("[Auth] Creating new device certificate"); auto request = ctx.request.get(); if (not request->verify()) { JAMI_ERR("[Auth] Invalid certificate request."); ctx.onFailure(AuthError::INVALID_ARGUMENTS, ""); return; } deviceCertificate = std::make_shared<dht::crypto::Certificate>( dht::crypto::Certificate::generate(*request, a.id)); JAMI_WARNING("[Auth] Created new device: {}", deviceCertificate->getLongId()); } auto receipt = makeReceipt(a.id, *deviceCertificate, ethAccount); auto receiptSignature = a.id.first->sign({receipt.first.begin(), receipt.first.end()}); auto info = std::make_unique<AccountInfo>(); auto pk = usePreviousIdentity ? ctx.credentials->updateIdentity.first : ctx.key.get(); auto sharedPk = pk->getSharedPublicKey(); info->identity.first = pk; info->identity.second = deviceCertificate; info->accountId = a.id.second->getId().toString(); info->devicePk = sharedPk; info->deviceId = info->devicePk->getLongId().toString(); if (ctx.deviceName.empty()) ctx.deviceName = info->deviceId.substr(8); if (!contacts) contacts = std::make_unique<ContactList>(ctx.accountId, a.id.second, path_, onChange_); info->contacts = std::move(contacts); info->contacts->setContacts(a.contacts); info->contacts->foundAccountDevice(deviceCertificate, ctx.deviceName, clock::now()); info->ethAccount = ethAccount; info->announce = std::move(receipt.second); ConversationModule::saveConvInfosToPath(path_, a.conversations); ConversationModule::saveConvRequestsToPath(path_, a.conversationsRequests); info_ = std::move(info); ctx.onSuccess(*info_, std::move(a.config), std::move(receipt.first), std::move(receiptSignature)); } std::pair<std::vector<uint8_t>, dht::InfoHash> ArchiveAccountManager::computeKeys(const std::string& password, const std::string& pin, bool previous) { // Compute time seed auto now = std::chrono::duration_cast<std::chrono::seconds>(clock::now().time_since_epoch()); auto tseed = now.count() / std::chrono::seconds(EXPORT_KEY_RENEWAL_TIME).count(); if (previous) tseed--; std::ostringstream ss; ss << std::hex << tseed; auto tseed_str = ss.str(); // Generate key for archive encryption, using PIN as the salt std::vector<uint8_t> salt_key; salt_key.reserve(pin.size() + tseed_str.size()); salt_key.insert(salt_key.end(), pin.begin(), pin.end()); salt_key.insert(salt_key.end(), tseed_str.begin(), tseed_str.end()); auto key = dht::crypto::stretchKey(password, salt_key, 256 / 8); // Generate public storage location as SHA1(key). auto loc = dht::InfoHash::get(key); return {key, loc}; } std::pair<std::string, std::shared_ptr<dht::Value>> ArchiveAccountManager::makeReceipt(const dht::crypto::Identity& id, const dht::crypto::Certificate& device, const std::string& ethAccount) { JAMI_DBG("[Auth] Signing device receipt"); auto devId = device.getId(); DeviceAnnouncement announcement; announcement.dev = devId; announcement.pk = device.getSharedPublicKey(); dht::Value ann_val {announcement}; ann_val.sign(*id.first); auto packedAnnoucement = ann_val.getPacked(); JAMI_DBG("[Auth] Device announcement size: %zu", packedAnnoucement.size()); std::ostringstream is; is << "{\"id\":\"" << id.second->getId() << "\",\"dev\":\"" << devId << "\",\"eth\":\"" << ethAccount << "\",\"announce\":\"" << base64::encode(packedAnnoucement) << "\"}"; // auto announce_ = ; return {is.str(), std::make_shared<dht::Value>(std::move(ann_val))}; } bool ArchiveAccountManager::needsMigration(const dht::crypto::Identity& id) { if (not id.second) return false; auto cert = id.second->issuer; while (cert) { if (not cert->isCA()) { JAMI_WARN("certificate %s is not a CA, needs update.", cert->getId().toString().c_str()); return true; } if (cert->getExpiration() < clock::now()) { JAMI_WARN("certificate %s is expired, needs update.", cert->getId().toString().c_str()); return true; } cert = cert->issuer; } return false; } void ArchiveAccountManager::syncDevices() { if (not dht_ or not dht_->isRunning()) { JAMI_WARN("Not syncing devices: DHT is not running"); return; } JAMI_DBG("Building device sync from %s", info_->deviceId.c_str()); auto sync_data = info_->contacts->getSyncData(); for (const auto& dev : getKnownDevices()) { // don't send sync data to ourself if (dev.first.toString() == info_->deviceId) continue; if (!dev.second.certificate) { JAMI_WARNING("Unable to find certificate for {}", dev.first); continue; } auto pk = dev.second.certificate->getSharedPublicKey(); JAMI_DBG("sending device sync to %s %s", dev.second.name.c_str(), dev.first.toString().c_str()); auto syncDeviceKey = dht::InfoHash::get("inbox:" + pk->getId().toString()); dht_->putEncrypted(syncDeviceKey, pk, sync_data); } } void ArchiveAccountManager::startSync(const OnNewDeviceCb& cb, const OnDeviceAnnouncedCb& dcb, bool publishPresence) { AccountManager::startSync(std::move(cb), std::move(dcb), publishPresence); dht_->listen<DeviceSync>( dht::InfoHash::get("inbox:" + info_->devicePk->getId().toString()), [this](DeviceSync&& sync) { // Received device sync data. // check device certificate findCertificate(sync.from, [this, sync](const std::shared_ptr<dht::crypto::Certificate>& cert) mutable { if (!cert or cert->getId() != sync.from) { JAMI_WARN("Unable to find certificate for device %s", sync.from.toString().c_str()); return; } if (not foundAccountDevice(cert)) return; onSyncData(std::move(sync)); }); return true; }); } AccountArchive ArchiveAccountManager::readArchive(std::string_view scheme, const std::string& pwd) const { JAMI_DBG("[Auth] Reading account archive"); return AccountArchive(fileutils::getFullPath(path_, archivePath_), scheme, pwd); } void ArchiveAccountManager::updateArchive(AccountArchive& archive) const { using namespace libjami::Account::ConfProperties; // Keys not exported to archive static const auto filtered_keys = {Ringtone::PATH, ARCHIVE_PATH, DEVICE_ID, DEVICE_NAME, Conf::CONFIG_DHT_PORT, DHT_PROXY_LIST_URL, AUTOANSWER, PROXY_ENABLED, PROXY_SERVER, PROXY_PUSH_TOKEN}; // Keys with meaning of file path where the contents has to be exported in base64 static const auto encoded_keys = {TLS::CA_LIST_FILE, TLS::CERTIFICATE_FILE, TLS::PRIVATE_KEY_FILE}; JAMI_DBG("[Auth] Building account archive"); for (const auto& it : onExportConfig_()) { // filter-out? if (std::any_of(std::begin(filtered_keys), std::end(filtered_keys), [&](const auto& key) { return key == it.first; })) continue; // file contents? if (std::any_of(std::begin(encoded_keys), std::end(encoded_keys), [&](const auto& key) { return key == it.first; })) { try { archive.config.emplace(it.first, base64::encode(fileutils::loadFile(it.second))); } catch (...) { } } else archive.config[it.first] = it.second; } if (info_) { // If migrating from same archive, info_ will be null archive.contacts = info_->contacts->getContacts(); // Note we do not know accountID_ here, use path archive.conversations = ConversationModule::convInfosFromPath(path_); archive.conversationsRequests = ConversationModule::convRequestsFromPath(path_); } } void ArchiveAccountManager::saveArchive(AccountArchive& archive, std::string_view scheme, const std::string& pwd) { try { updateArchive(archive); if (archivePath_.empty()) archivePath_ = "export.gz"; archive.save(fileutils::getFullPath(path_, archivePath_), scheme, pwd); } catch (const std::runtime_error& ex) { JAMI_ERR("[Auth] Unable to export archive: %s", ex.what()); return; } } bool ArchiveAccountManager::changePassword(const std::string& password_old, const std::string& password_new) { try { auto path = fileutils::getFullPath(path_, archivePath_); AccountArchive(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_old) .save(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_new); return true; } catch (const std::exception&) { return false; } } std::vector<uint8_t> ArchiveAccountManager::getPasswordKey(const std::string& password) { try { auto data = dhtnet::fileutils::loadFile(fileutils::getFullPath(path_, archivePath_)); // Try to decrypt to check if password is valid auto key = dht::crypto::aesGetKey(data, password); auto decrypted = dht::crypto::aesDecrypt(dht::crypto::aesGetEncrypted(data), key); return key; } catch (const std::exception& e) { JAMI_ERR("Error loading archive: %s", e.what()); } return {}; } std::string generatePIN(size_t length = 16, size_t split = 8) { static constexpr const char alphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::random_device rd; std::uniform_int_distribution<size_t> dis(0, sizeof(alphabet) - 2); std::string ret; ret.reserve(length); for (size_t i = 0; i < length; i++) { ret.push_back(alphabet[dis(rd)]); if (i % split == split - 1 and i != length - 1) ret.push_back('-'); } return ret; } void ArchiveAccountManager::addDevice(const std::string& password, AddDeviceCallback cb) { dht::ThreadPool::computation().run([password, cb = std::move(cb), w=weak_from_this()] { auto this_ = std::static_pointer_cast<ArchiveAccountManager>(w.lock()); if (not this_) return; std::vector<uint8_t> key; dht::InfoHash loc; std::string pin_str; AccountArchive a; try { JAMI_DBG("[Auth] Exporting account"); a = this_->readArchive("password", password); // Generate random PIN pin_str = generatePIN(); std::tie(key, loc) = computeKeys(password, pin_str); } catch (const std::exception& e) { JAMI_ERR("[Auth] Unable to export account: %s", e.what()); cb(AddDeviceResult::ERROR_CREDENTIALS, {}); return; } // now that key and loc are computed, display to user in lowercase std::transform(pin_str.begin(), pin_str.end(), pin_str.begin(), ::tolower); try { this_->updateArchive(a); auto encrypted = dht::crypto::aesEncrypt(archiver::compress(a.serialize()), key); if (not this_->dht_ or not this_->dht_->isRunning()) throw std::runtime_error("DHT is not running.."); JAMI_WARN("[Auth] Exporting account with PIN: %s at %s (size %zu)", pin_str.c_str(), loc.toString().c_str(), encrypted.size()); this_->dht_->put(loc, encrypted, [cb, pin = std::move(pin_str)](bool ok) { JAMI_DBG("[Auth] Account archive published: %s", ok ? "success" : "failure"); if (ok) cb(AddDeviceResult::SUCCESS_SHOW_PIN, pin); else cb(AddDeviceResult::ERROR_NETWORK, {}); }); } catch (const std::exception& e) { JAMI_ERR("[Auth] Unable to export account: %s", e.what()); cb(AddDeviceResult::ERROR_NETWORK, {}); return; } }); } bool ArchiveAccountManager::revokeDevice(const std::string& device, std::string_view scheme, const std::string& password, RevokeDeviceCallback cb) { auto fa = dht::ThreadPool::computation().getShared<AccountArchive>( [this, scheme=std::string(scheme), password] { return readArchive(scheme, password); }); findCertificate(DeviceId(device), [fa = std::move(fa), scheme=std::string(scheme), password, device, cb, w=weak_from_this()]( const std::shared_ptr<dht::crypto::Certificate>& crt) mutable { if (not crt) { cb(RevokeDeviceResult::ERROR_NETWORK); return; } auto this_ = std::static_pointer_cast<ArchiveAccountManager>(w.lock()); if (not this_) return; this_->info_->contacts->foundAccountDevice(crt); AccountArchive a; try { a = fa.get(); } catch (...) { cb(RevokeDeviceResult::ERROR_CREDENTIALS); return; } // Add revoked device to the revocation list and resign it if (not a.revoked) a.revoked = std::make_shared<decltype(a.revoked)::element_type>(); a.revoked->revoke(*crt); a.revoked->sign(a.id); // add to CRL cache this_->certStore().pinRevocationList(a.id.second->getId().toString(), a.revoked); this_->certStore().loadRevocations(*a.id.second); // Announce CRL immediately auto h = a.id.second->getId(); this_->dht_->put(h, a.revoked, dht::DoneCallback {}, {}, true); this_->saveArchive(a, scheme, password); this_->info_->contacts->removeAccountDevice(crt->getLongId()); cb(RevokeDeviceResult::SUCCESS); this_->syncDevices(); }); return false; } bool ArchiveAccountManager::exportArchive(const std::string& destinationPath, std::string_view scheme, const std::string& password) { try { // Save contacts if possible before exporting AccountArchive archive = readArchive(scheme, password); updateArchive(archive); auto archivePath = fileutils::getFullPath(path_, archivePath_); archive.save(archivePath, scheme, password); // Export the file std::error_code ec; std::filesystem::copy_file(archivePath, destinationPath, std::filesystem::copy_options::overwrite_existing, ec); return !ec; } catch (const std::runtime_error& ex) { JAMI_ERR("[Auth] Unable to export archive: %s", ex.what()); return false; } catch (...) { JAMI_ERR("[Auth] Unable to export archive: Unable to read archive"); return false; } } bool ArchiveAccountManager::isPasswordValid(const std::string& password) { try { readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password); return true; } catch (...) { return false; } } #if HAVE_RINGNS void ArchiveAccountManager::registerName(const std::string& name, std::string_view scheme, const std::string& password, RegistrationCallback cb) { std::string signedName; auto nameLowercase {name}; std::transform(nameLowercase.begin(), nameLowercase.end(), nameLowercase.begin(), ::tolower); std::string publickey; std::string accountId; std::string ethAccount; try { auto archive = readArchive(scheme, password); auto privateKey = archive.id.first; const auto& pk = privateKey->getPublicKey(); publickey = pk.toString(); accountId = pk.getId().toString(); signedName = base64::encode( privateKey->sign(std::vector<uint8_t>(nameLowercase.begin(), nameLowercase.end()))); ethAccount = dev::KeyPair(dev::Secret(archive.eth_key)).address().hex(); } catch (const std::exception& e) { // JAMI_ERR("[Auth] Unable to export account: %s", e.what()); cb(NameDirectory::RegistrationResponse::invalidCredentials, name); return; } nameDir_.get().registerName(accountId, nameLowercase, ethAccount, cb, signedName, publickey); } #endif } // namespace jami
33,252
C++
.cpp
766
32.45953
163
0.572429
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,794
jamiaccount_config.cpp
savoirfairelinux_jami-daemon/src/jamidht/jamiaccount_config.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "jamiaccount_config.h" #include "account_const.h" #include "account_schema.h" #include "configkeys.h" #include "fileutils.h" #include "config/account_config_utils.h" namespace jami { namespace Conf { constexpr const char* const TLS_KEY = "tls"; constexpr const char* CERTIFICATE_KEY = "certificate"; constexpr const char* CALIST_KEY = "calist"; const char* const TLS_PASSWORD_KEY = "password"; const char* const PRIVATE_KEY_KEY = "privateKey"; } // namespace Conf static const JamiAccountConfig DEFAULT_CONFIG {}; void JamiAccountConfig::serialize(YAML::Emitter& out) const { out << YAML::BeginMap; SipAccountBaseConfig::serializeDiff(out, DEFAULT_CONFIG); SERIALIZE_CONFIG(Conf::DHT_PORT_KEY, dhtPort); SERIALIZE_CONFIG(Conf::DHT_PUBLIC_IN_CALLS, allowPublicIncoming); SERIALIZE_CONFIG(Conf::DHT_ALLOW_PEERS_FROM_HISTORY, allowPeersFromHistory); SERIALIZE_CONFIG(Conf::DHT_ALLOW_PEERS_FROM_CONTACT, allowPeersFromContact); SERIALIZE_CONFIG(Conf::DHT_ALLOW_PEERS_FROM_TRUSTED, allowPeersFromTrusted); SERIALIZE_CONFIG(libjami::Account::ConfProperties::DHT_PEER_DISCOVERY, dhtPeerDiscovery); SERIALIZE_CONFIG(libjami::Account::ConfProperties::ACCOUNT_PEER_DISCOVERY, accountPeerDiscovery); SERIALIZE_CONFIG(libjami::Account::ConfProperties::ACCOUNT_PUBLISH, accountPublish); SERIALIZE_CONFIG(Conf::PROXY_ENABLED_KEY, proxyEnabled); SERIALIZE_CONFIG(Conf::PROXY_SERVER_KEY, proxyServer); SERIALIZE_CONFIG(libjami::Account::ConfProperties::PROXY_LIST_ENABLED, proxyListEnabled); SERIALIZE_CONFIG(libjami::Account::ConfProperties::DHT_PROXY_LIST_URL, proxyListUrl); SERIALIZE_CONFIG(libjami::Account::ConfProperties::RingNS::URI, nameServer); SERIALIZE_CONFIG(libjami::Account::VolatileProperties::REGISTERED_NAME, registeredName); SERIALIZE_PATH(libjami::Account::ConfProperties::ARCHIVE_PATH, archivePath); SERIALIZE_CONFIG(libjami::Account::ConfProperties::ARCHIVE_HAS_PASSWORD, archiveHasPassword); SERIALIZE_CONFIG(libjami::Account::ConfProperties::DEVICE_NAME, deviceName); SERIALIZE_CONFIG(libjami::Account::ConfProperties::MANAGER_URI, managerUri); SERIALIZE_CONFIG(libjami::Account::ConfProperties::MANAGER_USERNAME, managerUsername); SERIALIZE_CONFIG(libjami::Account::ConfProperties::DHT::PUBLIC_IN_CALLS, dhtPublicInCalls); out << YAML::Key << Conf::RING_ACCOUNT_RECEIPT << YAML::Value << receipt; if (receiptSignature.size() > 0) out << YAML::Key << Conf::RING_ACCOUNT_RECEIPT_SIG << YAML::Value << YAML::Binary(receiptSignature.data(), receiptSignature.size()); // tls submap out << YAML::Key << Conf::TLS_KEY << YAML::Value << YAML::BeginMap; SERIALIZE_PATH(Conf::CALIST_KEY, tlsCaListFile); SERIALIZE_PATH(Conf::CERTIFICATE_KEY, tlsCertificateFile); SERIALIZE_CONFIG(Conf::TLS_PASSWORD_KEY, tlsPassword); SERIALIZE_PATH(Conf::PRIVATE_KEY_KEY, tlsPrivateKeyFile); out << YAML::EndMap; out << YAML::EndMap; } void JamiAccountConfig::unserialize(const YAML::Node& node) { using yaml_utils::parseValueOptional; using yaml_utils::parsePathOptional; SipAccountBaseConfig::unserialize(node); // get tls submap try { const auto& tlsMap = node[Conf::TLS_KEY]; parsePathOptional(tlsMap, Conf::CERTIFICATE_KEY, tlsCertificateFile, path); parsePathOptional(tlsMap, Conf::CALIST_KEY, tlsCaListFile, path); parseValueOptional(tlsMap, Conf::TLS_PASSWORD_KEY, tlsPassword); parsePathOptional(tlsMap, Conf::PRIVATE_KEY_KEY, tlsPrivateKeyFile, path); } catch (...) { } parseValueOptional(node, Conf::DHT_PORT_KEY, dhtPort); parseValueOptional(node, Conf::DHT_ALLOW_PEERS_FROM_HISTORY, allowPeersFromHistory); parseValueOptional(node, Conf::DHT_ALLOW_PEERS_FROM_CONTACT, allowPeersFromContact); parseValueOptional(node, Conf::DHT_ALLOW_PEERS_FROM_TRUSTED, allowPeersFromTrusted); parseValueOptional(node, Conf::PROXY_ENABLED_KEY, proxyEnabled); parseValueOptional(node, Conf::PROXY_SERVER_KEY, proxyServer); parseValueOptional(node, libjami::Account::ConfProperties::DHT_PROXY_LIST_URL, proxyListUrl); parseValueOptional(node, libjami::Account::ConfProperties::PROXY_LIST_ENABLED, proxyListEnabled); parseValueOptional(node, libjami::Account::ConfProperties::DEVICE_NAME, deviceName); parseValueOptional(node, libjami::Account::ConfProperties::MANAGER_URI, managerUri); parseValueOptional(node, libjami::Account::ConfProperties::MANAGER_USERNAME, managerUsername); parseValueOptional(node, libjami::Account::ConfProperties::DHT::PUBLIC_IN_CALLS, dhtPublicInCalls); parsePathOptional(node, libjami::Account::ConfProperties::ARCHIVE_PATH, archivePath, path); parseValueOptional(node, libjami::Account::ConfProperties::ARCHIVE_HAS_PASSWORD, archiveHasPassword); try { parseValueOptional(node, Conf::RING_ACCOUNT_RECEIPT, receipt); auto receipt_sig = node[Conf::RING_ACCOUNT_RECEIPT_SIG].as<YAML::Binary>(); receiptSignature = {receipt_sig.data(), receipt_sig.data() + receipt_sig.size()}; } catch (const std::exception& e) { JAMI_WARN("Unable to read receipt: %s", e.what()); } parseValueOptional(node, libjami::Account::ConfProperties::DHT_PEER_DISCOVERY, dhtPeerDiscovery); parseValueOptional(node, libjami::Account::ConfProperties::ACCOUNT_PEER_DISCOVERY, accountPeerDiscovery); parseValueOptional(node, libjami::Account::ConfProperties::ACCOUNT_PUBLISH, accountPublish); parseValueOptional(node, libjami::Account::ConfProperties::RingNS::URI, nameServer); parseValueOptional(node, libjami::Account::VolatileProperties::REGISTERED_NAME, registeredName); parseValueOptional(node, Conf::DHT_PUBLIC_IN_CALLS, allowPublicIncoming); } std::map<std::string, std::string> JamiAccountConfig::toMap() const { std::map<std::string, std::string> a = SipAccountBaseConfig::toMap(); a.emplace(Conf::CONFIG_DHT_PORT, std::to_string(dhtPort)); a.emplace(Conf::CONFIG_DHT_PUBLIC_IN_CALLS, allowPublicIncoming ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::DHT_PEER_DISCOVERY, dhtPeerDiscovery ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::ACCOUNT_PEER_DISCOVERY, accountPeerDiscovery ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::ACCOUNT_PUBLISH, accountPublish ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::DEVICE_NAME, deviceName); a.emplace(libjami::Account::ConfProperties::Presence::SUPPORT_SUBSCRIBE, TRUE_STR); if (not archivePath.empty() or not managerUri.empty()) a.emplace(libjami::Account::ConfProperties::ARCHIVE_HAS_PASSWORD, archiveHasPassword ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TLS_CA_LIST_FILE, fileutils::getFullPath(path, tlsCaListFile).string()); a.emplace(Conf::CONFIG_TLS_CERTIFICATE_FILE, fileutils::getFullPath(path, tlsCertificateFile).string()); a.emplace(Conf::CONFIG_TLS_PRIVATE_KEY_FILE, fileutils::getFullPath(path, tlsPrivateKeyFile).string()); a.emplace(Conf::CONFIG_TLS_PASSWORD, tlsPassword); a.emplace(libjami::Account::ConfProperties::ALLOW_CERT_FROM_HISTORY, allowPeersFromHistory ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::ALLOW_CERT_FROM_CONTACT, allowPeersFromContact ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::ALLOW_CERT_FROM_TRUSTED, allowPeersFromTrusted ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::PROXY_ENABLED, proxyEnabled ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::PROXY_LIST_ENABLED, proxyListEnabled ? TRUE_STR : FALSE_STR); a.emplace(libjami::Account::ConfProperties::PROXY_SERVER, proxyServer); a.emplace(libjami::Account::ConfProperties::DHT_PROXY_LIST_URL, proxyListUrl); a.emplace(libjami::Account::ConfProperties::MANAGER_URI, managerUri); a.emplace(libjami::Account::ConfProperties::MANAGER_USERNAME, managerUsername); a.emplace(libjami::Account::ConfProperties::DHT::PUBLIC_IN_CALLS, dhtPublicInCalls ? TRUE_STR : FALSE_STR); #if HAVE_RINGNS a.emplace(libjami::Account::ConfProperties::RingNS::URI, nameServer); #endif return a; } void JamiAccountConfig::fromMap(const std::map<std::string, std::string>& details) { SipAccountBaseConfig::fromMap(details); // TLS parsePath(details, Conf::CONFIG_TLS_CA_LIST_FILE, tlsCaListFile, path); parsePath(details, Conf::CONFIG_TLS_CERTIFICATE_FILE, tlsCertificateFile, path); parsePath(details, Conf::CONFIG_TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile, path); parseString(details, Conf::CONFIG_TLS_PASSWORD, tlsPassword); if (hostname.empty()) hostname = DHT_DEFAULT_BOOTSTRAP; parseString(details, libjami::Account::ConfProperties::BOOTSTRAP_LIST_URL, bootstrapListUrl); parseInt(details, Conf::CONFIG_DHT_PORT, dhtPort); parseBool(details, Conf::CONFIG_DHT_PUBLIC_IN_CALLS, allowPublicIncoming); parseBool(details, libjami::Account::ConfProperties::DHT_PEER_DISCOVERY, dhtPeerDiscovery); parseBool(details, libjami::Account::ConfProperties::ACCOUNT_PEER_DISCOVERY, accountPeerDiscovery); parseBool(details, libjami::Account::ConfProperties::ACCOUNT_PUBLISH, accountPublish); parseBool(details, libjami::Account::ConfProperties::ALLOW_CERT_FROM_HISTORY, allowPeersFromHistory); parseBool(details, libjami::Account::ConfProperties::ALLOW_CERT_FROM_CONTACT, allowPeersFromContact); parseBool(details, libjami::Account::ConfProperties::ALLOW_CERT_FROM_TRUSTED, allowPeersFromTrusted); parseString(details, libjami::Account::ConfProperties::MANAGER_URI, managerUri); parseString(details, libjami::Account::ConfProperties::MANAGER_USERNAME, managerUsername); parseBool(details, libjami::Account::ConfProperties::DHT::PUBLIC_IN_CALLS, dhtPublicInCalls); // parseString(details, libjami::Account::ConfProperties::USERNAME, username); parseString(details, libjami::Account::ConfProperties::ARCHIVE_PASSWORD, credentials.archive_password); parseString(details, libjami::Account::ConfProperties::ARCHIVE_PASSWORD_SCHEME, credentials.archive_password_scheme); parseString(details, libjami::Account::ConfProperties::ARCHIVE_PIN, credentials.archive_pin); std::transform(credentials.archive_pin.begin(), credentials.archive_pin.end(), credentials.archive_pin.begin(), ::toupper); parseString(details, libjami::Account::ConfProperties::ARCHIVE_PATH, credentials.archive_path); parseString(details, libjami::Account::ConfProperties::DEVICE_NAME, deviceName); auto oldProxyServer = proxyServer, oldProxyServerList = proxyListUrl; parseString(details, libjami::Account::ConfProperties::DHT_PROXY_LIST_URL, proxyListUrl); parseBool(details, libjami::Account::ConfProperties::PROXY_ENABLED, proxyEnabled); parseBool(details, libjami::Account::ConfProperties::PROXY_LIST_ENABLED, proxyListEnabled); parseString(details, libjami::Account::ConfProperties::PROXY_SERVER, proxyServer); parseString(details, libjami::Account::ConfProperties::UI_CUSTOMIZATION, uiCustomization); if (not managerUri.empty() and managerUri.rfind("http", 0) != 0) { managerUri = "https://" + managerUri; } #if HAVE_RINGNS parseString(details, libjami::Account::ConfProperties::RingNS::URI, nameServer); #endif } } // namespace jami
12,451
C++
.cpp
209
53.904306
127
0.743842
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,795
conversation_module.cpp
savoirfairelinux_jami-daemon/src/jamidht/conversation_module.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "conversation_module.h" #include <algorithm> #include <fstream> #include <opendht/thread_pool.h> #include "account_const.h" #include "call.h" #include "client/ring_signal.h" #include "fileutils.h" #include "jamidht/account_manager.h" #include "jamidht/jamiaccount.h" #include "manager.h" #include "sip/sipcall.h" #include "vcard.h" namespace jami { using ConvInfoMap = std::map<std::string, ConvInfo>; struct PendingConversationFetch { bool ready {false}; bool cloning {false}; std::string deviceId {}; std::string removeId {}; std::map<std::string, std::string> preferences {}; std::map<std::string, std::map<std::string, std::string>> status {}; std::set<std::string> connectingTo {}; std::shared_ptr<dhtnet::ChannelSocket> socket {}; }; constexpr std::chrono::seconds MAX_FALLBACK {12 * 3600s}; struct SyncedConversation { std::mutex mtx; std::unique_ptr<asio::steady_timer> fallbackClone; std::chrono::seconds fallbackTimer {5s}; ConvInfo info; std::unique_ptr<PendingConversationFetch> pending; std::shared_ptr<Conversation> conversation; SyncedConversation(const std::string& convId) : info {convId} { fallbackClone = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext()); } SyncedConversation(const ConvInfo& info) : info {info} { fallbackClone = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext()); } bool startFetch(const std::string& deviceId, bool checkIfConv = false) { // conversation mtx must be locked if (checkIfConv && conversation) return false; // Already a conversation if (pending) { if (pending->ready) return false; // Already doing stuff // if (pending->deviceId == deviceId) // return false; // Already fetching if (pending->connectingTo.find(deviceId) != pending->connectingTo.end()) return false; // Already connecting to this device } else { pending = std::make_unique<PendingConversationFetch>(); pending->connectingTo.insert(deviceId); return true; } return true; } void stopFetch(const std::string& deviceId) { // conversation mtx must be locked if (!pending) return; pending->connectingTo.erase(deviceId); if (pending->connectingTo.empty()) pending.reset(); } std::vector<std::map<std::string, std::string>> getMembers(bool includeLeft, bool includeBanned) const { // conversation mtx must be locked if (conversation) return conversation->getMembers(true, includeLeft, includeBanned); // If we're cloning, we can return the initial members std::vector<std::map<std::string, std::string>> result; result.reserve(info.members.size()); for (const auto& uri : info.members) { result.emplace_back(std::map<std::string, std::string> {{"uri", uri}}); } return result; } }; class ConversationModule::Impl : public std::enable_shared_from_this<Impl> { public: Impl(std::shared_ptr<JamiAccount>&& account, std::shared_ptr<AccountManager>&& accountManager, NeedsSyncingCb&& needsSyncingCb, SengMsgCb&& sendMsgCb, NeedSocketCb&& onNeedSocket, NeedSocketCb&& onNeedSwarmSocket, OneToOneRecvCb&& oneToOneRecvCb); template<typename S, typename T> inline auto withConv(const S& convId, T&& cb) const { if (auto conv = getConversation(convId)) { std::lock_guard lk(conv->mtx); return cb(*conv); } else { JAMI_WARNING("Conversation {} not found", convId); } return decltype(cb(std::declval<SyncedConversation&>()))(); } template<typename S, typename T> inline auto withConversation(const S& convId, T&& cb) { if (auto conv = getConversation(convId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return cb(*conv->conversation); } else { JAMI_WARNING("Conversation {} not found", convId); } return decltype(cb(std::declval<Conversation&>()))(); } // Retrieving recent commits /** * Clone a conversation (initial) from device * @param deviceId * @param convId */ void cloneConversation(const std::string& deviceId, const std::string& peer, const std::string& convId); void cloneConversation(const std::string& deviceId, const std::string& peer, const std::shared_ptr<SyncedConversation>& conv); /** * Pull remote device * @param peer Contact URI * @param deviceId Contact's device * @param conversationId * @param commitId (optional) */ void fetchNewCommits(const std::string& peer, const std::string& deviceId, const std::string& conversationId, const std::string& commitId = ""); /** * Handle events to receive new commits */ void handlePendingConversation(const std::string& conversationId, const std::string& deviceId); // Requests std::optional<ConversationRequest> getRequest(const std::string& id) const; // Conversations /** * Get members * @param conversationId * @param includeBanned * @return a map of members with their role and details */ std::vector<std::map<std::string, std::string>> getConversationMembers( const std::string& conversationId, bool includeBanned = false) const; void setConversationMembers(const std::string& convId, const std::set<std::string>& members); /** * Remove a repository and all files * @param convId * @param sync If we send an update to other account's devices * @param force True if ignore the removing flag */ void removeRepository(const std::string& convId, bool sync, bool force = false); void removeRepositoryImpl(SyncedConversation& conv, bool sync, bool force = false); /** * Remove a conversation * @param conversationId */ bool removeConversation(const std::string& conversationId); bool removeConversationImpl(SyncedConversation& conv); /** * Send a message notification to all members * @param conversation * @param commit * @param sync If we send an update to other account's devices * @param deviceId If we need to filter a specific device */ void sendMessageNotification(const std::string& conversationId, bool sync, const std::string& commitId = "", const std::string& deviceId = ""); void sendMessageNotification(Conversation& conversation, bool sync, const std::string& commitId = "", const std::string& deviceId = ""); /** * @return if a convId is a valid conversation (repository cloned & usable) */ bool isConversation(const std::string& convId) const { std::lock_guard lk(conversationsMtx_); auto c = conversations_.find(convId); return c != conversations_.end() && c->second; } void addConvInfo(const ConvInfo& info) { std::lock_guard lk(convInfosMtx_); convInfos_[info.id] = info; saveConvInfos(); } std::string getOneToOneConversation(const std::string& uri) const noexcept; bool updateConvForContact(const std::string& uri, const std::string& oldConv, const std::string& newConv); std::shared_ptr<SyncedConversation> getConversation(std::string_view convId) const { std::lock_guard lk(conversationsMtx_); auto c = conversations_.find(convId); return c != conversations_.end() ? c->second : nullptr; } std::shared_ptr<SyncedConversation> getConversation(std::string_view convId) { std::lock_guard lk(conversationsMtx_); auto c = conversations_.find(convId); return c != conversations_.end() ? c->second : nullptr; } std::shared_ptr<SyncedConversation> startConversation(const std::string& convId) { std::lock_guard lk(conversationsMtx_); auto& c = conversations_[convId]; if (!c) c = std::make_shared<SyncedConversation>(convId); return c; } std::shared_ptr<SyncedConversation> startConversation(const ConvInfo& info) { std::lock_guard lk(conversationsMtx_); auto& c = conversations_[info.id]; if (!c) c = std::make_shared<SyncedConversation>(info); return c; } std::vector<std::shared_ptr<SyncedConversation>> getSyncedConversations() const { std::lock_guard lk(conversationsMtx_); std::vector<std::shared_ptr<SyncedConversation>> result; result.reserve(conversations_.size()); for (const auto& [_, c] : conversations_) result.emplace_back(c); return result; } std::vector<std::shared_ptr<Conversation>> getConversations() const { std::lock_guard lk(conversationsMtx_); std::vector<std::shared_ptr<Conversation>> result; result.reserve(conversations_.size()); for (const auto& [_, sc] : conversations_) { if (auto c = sc->conversation) result.emplace_back(std::move(c)); } return result; } // Message send/load void sendMessage(const std::string& conversationId, Json::Value&& value, const std::string& replyTo = "", bool announce = true, OnCommitCb&& onCommit = {}, OnDoneCb&& cb = {}); void sendMessage(const std::string& conversationId, std::string message, const std::string& replyTo = "", const std::string& type = "text/plain", bool announce = true, OnCommitCb&& onCommit = {}, OnDoneCb&& cb = {}); void editMessage(const std::string& conversationId, const std::string& newBody, const std::string& editedId); void bootstrapCb(std::string convId); // The following methods modify what is stored on the disk /** * @note convInfosMtx_ should be locked */ void saveConvInfos() const { ConversationModule::saveConvInfos(accountId_, convInfos_); } /** * @note conversationsRequestsMtx_ should be locked */ void saveConvRequests() const { ConversationModule::saveConvRequests(accountId_, conversationsRequests_); } void declineOtherConversationWith(const std::string& uri) noexcept; bool addConversationRequest(const std::string& id, const ConversationRequest& req) { // conversationsRequestsMtx_ MUST BE LOCKED if (isConversation(id)) return false; auto it = conversationsRequests_.find(id); if (it != conversationsRequests_.end()) { // We only remove requests (if accepted) or change .declined if (!req.declined) return false; } else if (req.isOneToOne()) { // Check that we're not adding a second one to one trust request // NOTE: If a new one to one request is received, we can decline the previous one. declineOtherConversationWith(req.from); } JAMI_DEBUG("Adding conversation request from {} ({})", req.from, id); conversationsRequests_[id] = req; saveConvRequests(); return true; } void rmConversationRequest(const std::string& id) { // conversationsRequestsMtx_ MUST BE LOCKED auto it = conversationsRequests_.find(id); if (it != conversationsRequests_.end()) { auto& md = syncingMetadatas_[id]; md = it->second.metadatas; md["syncing"] = "true"; md["created"] = std::to_string(it->second.received); } saveMetadatas(); conversationsRequests_.erase(id); saveConvRequests(); } std::weak_ptr<JamiAccount> account_; std::shared_ptr<AccountManager> accountManager_; NeedsSyncingCb needsSyncingCb_; SengMsgCb sendMsgCb_; NeedSocketCb onNeedSocket_; NeedSocketCb onNeedSwarmSocket_; OneToOneRecvCb oneToOneRecvCb_; std::string accountId_ {}; std::string deviceId_ {}; std::string username_ {}; // Requests mutable std::mutex conversationsRequestsMtx_; std::map<std::string, ConversationRequest> conversationsRequests_; // Conversations mutable std::mutex conversationsMtx_ {}; std::map<std::string, std::shared_ptr<SyncedConversation>, std::less<>> conversations_; // The following information are stored on the disk mutable std::mutex convInfosMtx_; // Note, should be locked after conversationsMtx_ if needed std::map<std::string, ConvInfo> convInfos_; // When sending a new message, we need to send the notification to some peers of the // conversation However, the conversation may be not bootstraped, so the list will be empty. // notSyncedNotification_ will store the notifiaction to announce until we have peers to sync // with. std::mutex notSyncedNotificationMtx_; std::map<std::string, std::string> notSyncedNotification_; std::weak_ptr<Impl> weak() { return std::static_pointer_cast<Impl>(shared_from_this()); } // Replay conversations (after erasing/re-adding) std::mutex replayMtx_; std::map<std::string, std::vector<std::map<std::string, std::string>>> replay_; std::map<std::string, uint64_t> refreshMessage; std::atomic_int syncCnt {0}; #ifdef LIBJAMI_TESTABLE std::function<void(std::string, Conversation::BootstrapStatus)> bootstrapCbTest_; #endif void fixStructures( std::shared_ptr<JamiAccount> account, const std::vector<std::tuple<std::string, std::string, std::string>>& updateContactConv, const std::set<std::string>& toRm); void cloneConversationFrom(const std::shared_ptr<SyncedConversation> conv, const std::string& deviceId, const std::string& oldConvId = ""); void bootstrap(const std::string& convId); void fallbackClone(const asio::error_code& ec, const std::string& conversationId); void cloneConversationFrom(const std::string& conversationId, const std::string& uri, const std::string& oldConvId = ""); // While syncing, we do not want to lose metadata (avatar/title and mode) std::map<std::string, std::map<std::string, std::string>> syncingMetadatas_; void saveMetadatas() { auto path = fileutils::get_data_dir() / accountId_; std::ofstream file(path / "syncingMetadatas", std::ios::trunc | std::ios::binary); msgpack::pack(file, syncingMetadatas_); } void loadMetadatas() { try { // read file auto path = fileutils::get_data_dir() / accountId_; std::lock_guard lock(dhtnet::fileutils::getFileLock(path / "syncingMetadatas")); auto file = fileutils::loadFile("syncingMetadatas", path); // load values msgpack::unpacked result; msgpack::unpack(result, (const char*) file.data(), file.size(), 0); result.get().convert(syncingMetadatas_); } catch (const std::exception& e) { JAMI_WARNING("[ConversationModule] error loading syncingMetadatas_: {}", e.what()); } } }; ConversationModule::Impl::Impl(std::shared_ptr<JamiAccount>&& account, std::shared_ptr<AccountManager>&& accountManager, NeedsSyncingCb&& needsSyncingCb, SengMsgCb&& sendMsgCb, NeedSocketCb&& onNeedSocket, NeedSocketCb&& onNeedSwarmSocket, OneToOneRecvCb&& oneToOneRecvCb) : account_(account) , accountManager_(accountManager) , needsSyncingCb_(needsSyncingCb) , sendMsgCb_(sendMsgCb) , onNeedSocket_(onNeedSocket) , onNeedSwarmSocket_(onNeedSwarmSocket) , oneToOneRecvCb_(oneToOneRecvCb) , accountId_(account->getAccountID()) { if (auto accm = account->accountManager()) if (const auto* info = accm->getInfo()) { deviceId_ = info->deviceId; username_ = info->accountId; } conversationsRequests_ = convRequests(accountId_); loadMetadatas(); } void ConversationModule::Impl::cloneConversation(const std::string& deviceId, const std::string& peerUri, const std::string& convId) { JAMI_DEBUG("[Account {}] Clone conversation on device {}", accountId_, deviceId); auto conv = startConversation(convId); std::unique_lock lk(conv->mtx); cloneConversation(deviceId, peerUri, conv); } void ConversationModule::Impl::cloneConversation(const std::string& deviceId, const std::string& peerUri, const std::shared_ptr<SyncedConversation>& conv) { // conv->mtx must be locked if (!conv->conversation) { // Note: here we don't return and connect to all members // the first that will successfully connect will be used for // cloning. // This avoid the case when we try to clone from convInfos + sync message // at the same time. if (!conv->startFetch(deviceId, true)) { JAMI_WARNING("[Account {}] Already fetching {}", accountId_, conv->info.id); addConvInfo(conv->info); return; } onNeedSocket_( conv->info.id, deviceId, [w = weak(), conv, deviceId](const auto& channel) { std::lock_guard lk(conv->mtx); if (conv->pending && !conv->pending->ready) { if (channel) { conv->pending->ready = true; conv->pending->deviceId = channel->deviceId().toString(); conv->pending->socket = channel; if (!conv->pending->cloning) { conv->pending->cloning = true; dht::ThreadPool::io().run([w, convId = conv->info.id, deviceId = conv->pending->deviceId]() { if (auto sthis = w.lock()) sthis->handlePendingConversation(convId, deviceId); }); } return true; } else { conv->stopFetch(deviceId); } } return false; }, MIME_TYPE_GIT); JAMI_LOG("[Account {}] New conversation detected: {}. Ask device {} to clone it", accountId_, conv->info.id, deviceId); conv->info.members.emplace(username_); conv->info.members.emplace(peerUri); addConvInfo(conv->info); } else { JAMI_DEBUG("[Account {}] Already have conversation {}", accountId_, conv->info.id); } } void ConversationModule::Impl::fetchNewCommits(const std::string& peer, const std::string& deviceId, const std::string& conversationId, const std::string& commitId) { { std::lock_guard lk(convInfosMtx_); auto itConv = convInfos_.find(conversationId); if (itConv != convInfos_.end() && itConv->second.isRemoved()) { // If the conversation is removed and we receives a new commit, // it means that the contact was removed but not banned. // If he wants a new conversation, they must removes/re-add the contact who declined. JAMI_WARNING("[Account {:s}] Received a commit for {}, but conversation is removed", accountId_, conversationId); return; } } std::optional<ConversationRequest> oldReq; { std::lock_guard lk(conversationsRequestsMtx_); oldReq = getRequest(conversationId); if (oldReq != std::nullopt && oldReq->declined) { JAMI_DEBUG("[Account {}] Received a request for a conversation already declined.", accountId_); return; } } JAMI_DEBUG("[Account {:s}] fetch commits from {:s}, for {:s}, commit {:s}", accountId_, peer, conversationId, commitId); auto conv = getConversation(conversationId); if (!conv) { JAMI_WARNING("[Account {}] Unable to find conversation {}, ask for an invite", accountId_, conversationId); sendMsgCb_(peer, {}, std::map<std::string, std::string> {{MIME_TYPE_INVITE, conversationId}}, 0); return; } std::unique_lock lk(conv->mtx); if (conv->conversation) { // Check if we already have the commit if (not commitId.empty() && conv->conversation->getCommit(commitId) != std::nullopt) { return; } if (conv->conversation->isRemoving()) { JAMI_WARNING("[Account {}] Conversation {} is being removed", accountId_, conversationId); return; } if (!conv->conversation->isMember(peer, true)) { JAMI_WARNING("[Account {}] {} is not a member of {}", accountId_, peer, conversationId); return; } if (conv->conversation->isBanned(deviceId)) { JAMI_WARNING("[Account {}] {} is a banned device in conversation {}", accountId_, deviceId, conversationId); return; } // Retrieve current last message auto lastMessageId = conv->conversation->lastCommitId(); if (lastMessageId.empty()) { JAMI_ERROR("[Account {}] No message detected. This is a bug", accountId_); return; } if (!conv->startFetch(deviceId)) { JAMI_WARNING("[Account {}] Already fetching {}", accountId_, conversationId); return; } syncCnt.fetch_add(1); onNeedSocket_( conversationId, deviceId, [w = weak(), conv, conversationId = std::move(conversationId), peer = std::move(peer), deviceId = std::move(deviceId), commitId = std::move(commitId)](const auto& channel) { auto sthis = w.lock(); auto acc = sthis ? sthis->account_.lock() : nullptr; std::unique_lock lk(conv->mtx); auto conversation = conv->conversation; if (!channel || !acc || !conversation) { conv->stopFetch(deviceId); if (sthis) sthis->syncCnt.fetch_sub(1); return false; } conversation->addGitSocket(channel->deviceId(), channel); lk.unlock(); conversation->sync( peer, deviceId, [w, conv, conversationId = std::move(conversationId), peer = std::move(peer), deviceId = std::move(deviceId), commitId = std::move(commitId)](bool ok) { auto shared = w.lock(); if (!shared) return; if (!ok) { JAMI_WARNING("[Account {}] Unable to fetch new commit from " "{} for {}, other " "peer may be disconnected", shared->accountId_, deviceId, conversationId); JAMI_LOG("[Account {}] Relaunch sync with {} for {}", shared->accountId_, deviceId, conversationId); } { std::lock_guard lk(conv->mtx); conv->pending.reset(); // Notify peers that a new commit is there (DRT) if (not commitId.empty() && ok) { shared->sendMessageNotification(*conv->conversation, false, commitId, deviceId); } } if (shared->syncCnt.fetch_sub(1) == 1) { emitSignal<libjami::ConversationSignal::ConversationSyncFinished>(shared->accountId_); } }, commitId); return true; }, ""); } else { if (oldReq != std::nullopt) return; if (conv->pending) return; bool clone = !conv->info.isRemoved(); if (clone) { cloneConversation(deviceId, peer, conv); return; } lk.unlock(); JAMI_WARNING("[Account {}] Unable to find conversation {}, ask for an invite", accountId_, conversationId); sendMsgCb_(peer, {}, std::map<std::string, std::string> {{MIME_TYPE_INVITE, conversationId}}, 0); } } // Clone and store conversation void ConversationModule::Impl::handlePendingConversation(const std::string& conversationId, const std::string& deviceId) { auto acc = account_.lock(); if (!acc) return; std::vector<DeviceId> kd; { std::unique_lock lk(conversationsMtx_); const auto& devices = accountManager_->getKnownDevices(); kd.reserve(devices.size()); for (const auto& [id, _] : devices) kd.emplace_back(id); } auto conv = getConversation(conversationId); if (!conv) return; std::unique_lock lk(conv->mtx, std::defer_lock); auto erasePending = [&] { std::string toRm; if (conv->pending && !conv->pending->removeId.empty()) toRm = std::move(conv->pending->removeId); conv->pending.reset(); lk.unlock(); if (!toRm.empty()) removeConversation(toRm); }; try { auto conversation = std::make_shared<Conversation>(acc, deviceId, conversationId); conversation->onMembersChanged([w=weak_from_this(), conversationId](const auto& members) { // Delay in another thread to avoid deadlocks dht::ThreadPool::io().run([w, conversationId, members = std::move(members)] { if (auto sthis = w.lock()) sthis->setConversationMembers(conversationId, members); }); }); conversation->onMessageStatusChanged([this, conversationId](const auto& status) { auto msg = std::make_shared<SyncMsg>(); msg->ms = {{conversationId, status}}; needsSyncingCb_(std::move(msg)); }); conversation->onNeedSocket(onNeedSwarmSocket_); if (!conversation->isMember(username_, true)) { JAMI_ERR("Conversation cloned but does not seems to be a valid member"); conversation->erase(); lk.lock(); erasePending(); return; } // Make sure that the list of members stored in convInfos_ matches the // one from the conversation's repository. // (https://git.jami.net/savoirfairelinux/jami-daemon/-/issues/1026) setConversationMembers(conversationId, conversation->memberUris("", {})); lk.lock(); if (conv->pending && conv->pending->socket) conversation->addGitSocket(DeviceId(deviceId), std::move(conv->pending->socket)); auto removeRepo = false; // Note: a removeContact while cloning. In this case, the conversation // must not be announced and removed. if (conv->info.isRemoved()) removeRepo = true; std::map<std::string, std::string> preferences; std::map<std::string, std::map<std::string, std::string>> status; if (conv->pending) { preferences = std::move(conv->pending->preferences); status = std::move(conv->pending->status); } conv->conversation = conversation; if (removeRepo) { removeRepositoryImpl(*conv, false, true); erasePending(); return; } auto commitId = conversation->join(); std::vector<std::map<std::string, std::string>> messages; { std::lock_guard lk(replayMtx_); auto replayIt = replay_.find(conversationId); if (replayIt != replay_.end()) { messages = std::move(replayIt->second); replay_.erase(replayIt); } } if (!commitId.empty()) sendMessageNotification(*conversation, false, commitId); erasePending(); // Will unlock #ifdef LIBJAMI_TESTABLE conversation->onBootstrapStatus(bootstrapCbTest_); #endif // LIBJAMI_TESTABLE conversation->bootstrap(std::bind(&ConversationModule::Impl::bootstrapCb, this, conversation->id()), kd); if (!preferences.empty()) conversation->updatePreferences(preferences); if (!status.empty()) conversation->updateMessageStatus(status); syncingMetadatas_.erase(conversationId); saveMetadatas(); // Inform user that the conversation is ready emitSignal<libjami::ConversationSignal::ConversationReady>(accountId_, conversationId); needsSyncingCb_({}); std::vector<Json::Value> values; values.reserve(messages.size()); for (const auto& message : messages) { // For now, only replay text messages. // File transfers will need more logic, and don't care about calls for now. if (message.at("type") == "text/plain" && message.at("author") == username_) { Json::Value json; json["body"] = message.at("body"); json["type"] = "text/plain"; values.emplace_back(std::move(json)); } } if (!values.empty()) conversation->sendMessages(std::move(values), [w = weak(), conversationId](const auto& commits) { auto shared = w.lock(); if (shared and not commits.empty()) shared->sendMessageNotification(conversationId, true, *commits.rbegin()); }); // Download members profile on first sync auto isOneOne = conversation->mode() == ConversationMode::ONE_TO_ONE; auto askForProfile = isOneOne; if (!isOneOne) { // If not 1:1 only download profiles from self (to avoid non checked files) auto cert = acc->certStore().getCertificate(deviceId); askForProfile = cert && cert->issuer && cert->issuer->getId().toString() == username_; } if (askForProfile) { for (const auto& member : conversation->memberUris(username_)) { acc->askForProfile(conversationId, deviceId, member); } } } catch (const std::exception& e) { JAMI_WARNING("Something went wrong when cloning conversation: {}. Re-clone in {}s", e.what(), conv->fallbackTimer.count()); conv->fallbackClone->expires_at(std::chrono::steady_clock::now() + conv->fallbackTimer); conv->fallbackTimer *= 2; if (conv->fallbackTimer > MAX_FALLBACK) conv->fallbackTimer = MAX_FALLBACK; conv->fallbackClone->async_wait( std::bind(&ConversationModule::Impl::fallbackClone, shared_from_this(), std::placeholders::_1, conversationId)); } lk.lock(); erasePending(); } std::optional<ConversationRequest> ConversationModule::Impl::getRequest(const std::string& id) const { // ConversationsRequestsMtx MUST BE LOCKED auto it = conversationsRequests_.find(id); if (it != conversationsRequests_.end()) return it->second; return std::nullopt; } std::string ConversationModule::Impl::getOneToOneConversation(const std::string& uri) const noexcept { auto details = accountManager_->getContactDetails(uri); auto itRemoved = details.find("removed"); // If contact is removed there is no conversation if (itRemoved != details.end() && itRemoved->second != "0") { auto itBanned = details.find("banned"); // If banned, conversation is still on disk if (itBanned == details.end() || itBanned->second == "0") { // Check if contact is removed auto itAdded = details.find("added"); if (std::stoi(itRemoved->second) > std::stoi(itAdded->second)) return {}; } } auto it = details.find(libjami::Account::TrustRequest::CONVERSATIONID); if (it != details.end()) return it->second; return {}; } bool ConversationModule::Impl::updateConvForContact(const std::string& uri, const std::string& oldConv, const std::string& newConv) { if (newConv != oldConv) { auto conversation = getOneToOneConversation(uri); if (conversation != oldConv) { JAMI_DEBUG("Old conversation is not found in details {} - found: {}", oldConv, conversation); return false; } accountManager_->updateContactConversation(uri, newConv); return true; } return false; } void ConversationModule::Impl::declineOtherConversationWith(const std::string& uri) noexcept { // conversationsRequestsMtx_ MUST BE LOCKED for (auto& [id, request] : conversationsRequests_) { if (request.declined) continue; // Ignore already declined requests if (request.isOneToOne() && request.from == uri) { JAMI_WARNING("Decline conversation request ({}) from {}", id, uri); request.declined = std::time(nullptr); syncingMetadatas_.erase(id); saveMetadatas(); emitSignal<libjami::ConversationSignal::ConversationRequestDeclined>(accountId_, id); } } } std::vector<std::map<std::string, std::string>> ConversationModule::Impl::getConversationMembers(const std::string& conversationId, bool includeBanned) const { return withConv(conversationId, [&](const auto& conv) { return conv.getMembers(true, includeBanned); }); } void ConversationModule::Impl::removeRepository(const std::string& conversationId, bool sync, bool force) { auto conv = getConversation(conversationId); if (!conv) return; std::unique_lock lk(conv->mtx); removeRepositoryImpl(*conv, sync, force); } void ConversationModule::Impl::removeRepositoryImpl(SyncedConversation& conv, bool sync, bool force) { if (conv.conversation && (force || conv.conversation->isRemoving())) { // Stop fetch! conv.pending.reset(); JAMI_LOG("Remove conversation: {}", conv.info.id); try { if (conv.conversation->mode() == ConversationMode::ONE_TO_ONE) { for (const auto& member : conv.conversation->getInitialMembers()) { if (member != username_) { // Note: this can happen while re-adding a contact. // In this case, check that we are removing the linked conversation. if (conv.info.id == getOneToOneConversation(member)) { accountManager_->removeContactConversation(member); } } } } } catch (const std::exception& e) { JAMI_ERR() << e.what(); } conv.conversation->erase(); conv.conversation.reset(); if (!sync) return; conv.info.erased = std::time(nullptr); needsSyncingCb_({}); addConvInfo(conv.info); } } bool ConversationModule::Impl::removeConversation(const std::string& conversationId) { return withConv(conversationId, [this](auto& conv) { return removeConversationImpl(conv); }); } bool ConversationModule::Impl::removeConversationImpl(SyncedConversation& conv) { auto members = conv.getMembers(false, false); auto isSyncing = !conv.conversation; auto hasMembers = !isSyncing // If syncing there is no member to inform && std::find_if(members.begin(), members.end(), [&](const auto& member) { return member.at("uri") == username_; }) != members.end() // We must be still a member && members.size() != 1; // If there is only ourself conv.info.removed = std::time(nullptr); if (isSyncing) conv.info.erased = std::time(nullptr); // Sync now, because it can take some time to really removes the datas needsSyncingCb_({}); addConvInfo(conv.info); emitSignal<libjami::ConversationSignal::ConversationRemoved>(accountId_, conv.info.id); if (isSyncing) return true; if (conv.conversation->mode() != ConversationMode::ONE_TO_ONE) { // For one to one, we do not notify the leave. The other can still generate request // and this is managed by the banned part. If we re-accept, the old conversation will be // retrieved auto commitId = conv.conversation->leave(); if (hasMembers) { JAMI_LOG("Wait that someone sync that user left conversation {}", conv.info.id); // Commit that we left if (!commitId.empty()) { // Do not sync as it's synched by convInfos sendMessageNotification(*conv.conversation, false, commitId); } else { JAMI_ERROR("Failed to send message to conversation {}", conv.info.id); } // In this case, we wait that another peer sync the conversation // to definitely remove it from the device. This is to inform the // peer that we left the conversation and never want to receive // any messages return true; } } else { for (const auto& m : members) if (username_ != m.at("uri")) updateConvForContact(m.at("uri"), conv.info.id, ""); } // Else we are the last member, so we can remove removeRepositoryImpl(conv, true); return true; } void ConversationModule::Impl::sendMessageNotification(const std::string& conversationId, bool sync, const std::string& commitId, const std::string& deviceId) { if (auto conv = getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) sendMessageNotification(*conv->conversation, sync, commitId, deviceId); } } void ConversationModule::Impl::sendMessageNotification(Conversation& conversation, bool sync, const std::string& commitId, const std::string& deviceId) { auto acc = account_.lock(); if (!acc) return; Json::Value message; auto commit = commitId == "" ? conversation.lastCommitId() : commitId; message["id"] = conversation.id(); message["commit"] = commit; message["deviceId"] = deviceId_; Json::StreamWriterBuilder builder; const auto text = Json::writeString(builder, message); // Send message notification will announce the new commit in 3 steps. // First, because our account can have several devices, announce to other devices if (sync) { // Announce to our devices refreshMessage[username_] = sendMsgCb_(username_, {}, std::map<std::string, std::string> { {MIME_TYPE_GIT, text}}, refreshMessage[username_]); } // Then, we announce to 2 random members in the conversation that aren't in the DRT // This allow new devices without the ability to sync to their other devices to sync with us. // Or they can also use an old backup. std::vector<std::string> nonConnectedMembers; std::vector<NodeId> devices; { std::lock_guard lk(notSyncedNotificationMtx_); devices = conversation.peersToSyncWith(); auto members = conversation.memberUris(username_, {MemberRole::BANNED}); std::vector<std::string> connectedMembers; // print all members for (const auto& device : devices) { auto cert = acc->certStore().getCertificate(device.toString()); if (cert && cert->issuer) connectedMembers.emplace_back(cert->issuer->getId().toString()); } std::sort(std::begin(connectedMembers), std::end(connectedMembers)); std::set_difference(members.begin(), members.end(), connectedMembers.begin(), connectedMembers.end(), std::inserter(nonConnectedMembers, nonConnectedMembers.begin())); std::shuffle(nonConnectedMembers.begin(), nonConnectedMembers.end(), acc->rand); if (nonConnectedMembers.size() > 2) nonConnectedMembers.resize(2); if (!conversation.isBootstraped()) { JAMI_DEBUG("[Conversation {}] Not yet bootstraped, save notification", conversation.id()); // Because we can get some git channels but not bootstraped, we should keep this // to refresh when bootstraped. notSyncedNotification_[conversation.id()] = commit; } } for (const auto& member : nonConnectedMembers) { refreshMessage[member] = sendMsgCb_(member, {}, std::map<std::string, std::string> { {MIME_TYPE_GIT, text}}, refreshMessage[member]); } // Finally we send to devices that the DRT choose. for (const auto& device : devices) { auto deviceIdStr = device.toString(); auto memberUri = conversation.uriFromDevice(deviceIdStr); if (memberUri.empty() || deviceIdStr == deviceId) continue; refreshMessage[deviceIdStr] = sendMsgCb_(memberUri, device, std::map<std::string, std::string> { {MIME_TYPE_GIT, text}}, refreshMessage[deviceIdStr]); } } void ConversationModule::Impl::sendMessage(const std::string& conversationId, std::string message, const std::string& replyTo, const std::string& type, bool announce, OnCommitCb&& onCommit, OnDoneCb&& cb) { Json::Value json; json["body"] = std::move(message); json["type"] = type; sendMessage(conversationId, std::move(json), replyTo, announce, std::move(onCommit), std::move(cb)); } void ConversationModule::Impl::sendMessage(const std::string& conversationId, Json::Value&& value, const std::string& replyTo, bool announce, OnCommitCb&& onCommit, OnDoneCb&& cb) { if (auto conv = getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) conv->conversation ->sendMessage(std::move(value), replyTo, std::move(onCommit), [this, conversationId, announce, cb = std::move(cb)](bool ok, const std::string& commitId) { if (cb) cb(ok, commitId); if (!announce) return; if (ok) sendMessageNotification(conversationId, true, commitId); else JAMI_ERR("Failed to send message to conversation %s", conversationId.c_str()); }); } } void ConversationModule::Impl::editMessage(const std::string& conversationId, const std::string& newBody, const std::string& editedId) { // Check that editedId is a valid commit, from ourself and plain/text auto validCommit = false; std::string type, tid; if (auto conv = getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { auto commit = conv->conversation->getCommit(editedId); if (commit != std::nullopt) { type = commit->at("type"); if (type == "application/data-transfer+json") tid = commit->at("tid"); validCommit = commit->at("author") == username_ && (type == "text/plain" || type == "application/data-transfer+json"); } } } if (!validCommit) { JAMI_ERROR("Unable to edit commit {:s}", editedId); return; } // Commit message edition Json::Value json; if (type == "application/data-transfer+json") { json["tid"] = ""; // Remove file! auto path = fileutils::get_data_dir() / accountId_ / "conversation_data" / conversationId / fmt::format("{}_{}", editedId, tid); dhtnet::fileutils::remove(path, true); } else { json["body"] = newBody; } json["edit"] = editedId; json["type"] = type; sendMessage(conversationId, std::move(json)); } void ConversationModule::Impl::bootstrapCb(std::string convId) { std::string commitId; { std::lock_guard lk(notSyncedNotificationMtx_); auto it = notSyncedNotification_.find(convId); if (it != notSyncedNotification_.end()) { commitId = it->second; notSyncedNotification_.erase(it); } } JAMI_DEBUG("[Conversation {}] Resend last message notification", convId); dht::ThreadPool::io().run([w = weak(), convId, commitId = std::move(commitId)] { if (auto sthis = w.lock()) sthis->sendMessageNotification(convId, true, commitId); }); } void ConversationModule::Impl::fixStructures( std::shared_ptr<JamiAccount> acc, const std::vector<std::tuple<std::string, std::string, std::string>>& updateContactConv, const std::set<std::string>& toRm) { for (const auto& [uri, oldConv, newConv] : updateContactConv) { updateConvForContact(uri, oldConv, newConv); } //////////////////////////////////////////////////////////////// // Note: This is only to homogeneize trust and convRequests std::vector<std::string> invalidPendingRequests; { auto requests = acc->getTrustRequests(); std::lock_guard lk(conversationsRequestsMtx_); for (const auto& request : requests) { auto itConvId = request.find(libjami::Account::TrustRequest::CONVERSATIONID); auto itConvFrom = request.find(libjami::Account::TrustRequest::FROM); if (itConvId != request.end() && itConvFrom != request.end()) { // Check if requests exists or is declined. auto itReq = conversationsRequests_.find(itConvId->second); auto declined = itReq == conversationsRequests_.end() || itReq->second.declined; if (declined) { JAMI_WARNING("Invalid trust request found: {:s}", itConvId->second); invalidPendingRequests.emplace_back(itConvFrom->second); } } } auto requestRemoved = false; for (auto it = conversationsRequests_.begin(); it != conversationsRequests_.end();) { if (it->second.from == username_) { JAMI_WARNING("Detected request from ourself, this makes no sense. Remove {}", it->first); it = conversationsRequests_.erase(it); } else { ++it; } } if (requestRemoved) { saveConvRequests(); } } for (const auto& invalidPendingRequest : invalidPendingRequests) acc->discardTrustRequest(invalidPendingRequest); //////////////////////////////////////////////////////////////// for (const auto& conv : toRm) { JAMI_ERROR("Remove conversation ({})", conv); removeConversation(conv); } JAMI_DEBUG("[Account {}] Conversations loaded!", accountId_); } void ConversationModule::Impl::cloneConversationFrom(const std::shared_ptr<SyncedConversation> conv, const std::string& deviceId, const std::string& oldConvId) { std::lock_guard lk(conv->mtx); const auto& conversationId = conv->info.id; if (!conv->startFetch(deviceId, true)) { JAMI_WARNING("[Account {}] Already fetching {}", accountId_, conversationId); return; } onNeedSocket_( conversationId, deviceId, [wthis=weak_from_this(), conv, conversationId, oldConvId, deviceId](const auto& channel) { std::lock_guard lk(conv->mtx); if (conv->pending && !conv->pending->ready) { conv->pending->removeId = oldConvId; if (channel) { conv->pending->ready = true; conv->pending->deviceId = channel->deviceId().toString(); conv->pending->socket = channel; if (!conv->pending->cloning) { conv->pending->cloning = true; dht::ThreadPool::io().run([wthis, conversationId, deviceId = conv->pending->deviceId]() { if (auto sthis = wthis.lock()) sthis->handlePendingConversation(conversationId, deviceId); }); } return true; } else if (auto sthis = wthis.lock()) { conv->stopFetch(deviceId); JAMI_WARNING("Clone failed. Re-clone in {}s", conv->fallbackTimer.count()); conv->fallbackClone->expires_at(std::chrono::steady_clock::now() + conv->fallbackTimer); conv->fallbackTimer *= 2; if (conv->fallbackTimer > MAX_FALLBACK) conv->fallbackTimer = MAX_FALLBACK; conv->fallbackClone->async_wait( std::bind(&ConversationModule::Impl::fallbackClone, sthis, std::placeholders::_1, conversationId)); } } return false; }, MIME_TYPE_GIT); } void ConversationModule::Impl::fallbackClone(const asio::error_code& ec, const std::string& conversationId) { if (ec == asio::error::operation_aborted) return; auto conv = getConversation(conversationId); if (!conv || conv->conversation) return; auto members = getConversationMembers(conversationId); for (const auto& member : members) if (member.at("uri") != username_) cloneConversationFrom(conversationId, member.at("uri")); } void ConversationModule::Impl::bootstrap(const std::string& convId) { std::vector<DeviceId> kd; { std::unique_lock lk(conversationsMtx_); const auto& devices = accountManager_->getKnownDevices(); kd.reserve(devices.size()); for (const auto& [id, _] : devices) kd.emplace_back(id); } auto bootstrap = [&](auto& conv) { if (conv) { #ifdef LIBJAMI_TESTABLE conv->onBootstrapStatus(bootstrapCbTest_); #endif // LIBJAMI_TESTABLE conv->bootstrap(std::bind(&ConversationModule::Impl::bootstrapCb, this, conv->id()), kd); } }; std::vector<std::string> toClone; if (convId.empty()) { std::lock_guard lk(convInfosMtx_); for (const auto& [conversationId, convInfo] : convInfos_) { auto conv = getConversation(conversationId); if (!conv) return; if ((!conv->conversation && !conv->info.isRemoved())) { // Because we're not tracking contact presence in order to sync now, // we need to ask to clone requests when bootstraping all conversations // else it can stay syncing toClone.emplace_back(conversationId); } else if (conv->conversation) { bootstrap(conv->conversation); } } } else if (auto conv = getConversation(convId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) bootstrap(conv->conversation); } for (const auto& cid : toClone) { auto members = getConversationMembers(cid); for (const auto& member : members) { if (member.at("uri") != username_) cloneConversationFrom(cid, member.at("uri")); } } } void ConversationModule::Impl::cloneConversationFrom(const std::string& conversationId, const std::string& uri, const std::string& oldConvId) { auto memberHash = dht::InfoHash(uri); if (!memberHash) { JAMI_WARNING("Invalid member detected: {}", uri); return; } auto conv = startConversation(conversationId); std::lock_guard lk(conv->mtx); conv->info = {conversationId}; conv->info.created = std::time(nullptr); conv->info.members.emplace(username_); conv->info.members.emplace(uri); accountManager_->forEachDevice( memberHash, [w = weak(), conv, conversationId, oldConvId]( const std::shared_ptr<dht::crypto::PublicKey>& pk) { auto sthis = w.lock(); auto deviceId = pk->getLongId().toString(); if (!sthis or deviceId == sthis->deviceId_) return; sthis->cloneConversationFrom(conv, deviceId, oldConvId); }); addConvInfo(conv->info); } //////////////////////////////////////////////////////////////// void ConversationModule::saveConvRequests( const std::string& accountId, const std::map<std::string, ConversationRequest>& conversationsRequests) { auto path = fileutils::get_data_dir() / accountId; saveConvRequestsToPath(path, conversationsRequests); } void ConversationModule::saveConvRequestsToPath( const std::filesystem::path& path, const std::map<std::string, ConversationRequest>& conversationsRequests) { auto p = path / "convRequests"; std::lock_guard lock(dhtnet::fileutils::getFileLock(p)); std::ofstream file(p, std::ios::trunc | std::ios::binary); msgpack::pack(file, conversationsRequests); } void ConversationModule::saveConvInfos(const std::string& accountId, const ConvInfoMap& conversations) { auto path = fileutils::get_data_dir() / accountId; saveConvInfosToPath(path, conversations); } void ConversationModule::saveConvInfosToPath(const std::filesystem::path& path, const ConvInfoMap& conversations) { std::ofstream file(path / "convInfo", std::ios::trunc | std::ios::binary); msgpack::pack(file, conversations); } //////////////////////////////////////////////////////////////// ConversationModule::ConversationModule(std::shared_ptr<JamiAccount> account, std::shared_ptr<AccountManager> accountManager, NeedsSyncingCb&& needsSyncingCb, SengMsgCb&& sendMsgCb, NeedSocketCb&& onNeedSocket, NeedSocketCb&& onNeedSwarmSocket, OneToOneRecvCb&& oneToOneRecvCb, bool autoLoadConversations) : pimpl_ {std::make_unique<Impl>(std::move(account), std::move(accountManager), std::move(needsSyncingCb), std::move(sendMsgCb), std::move(onNeedSocket), std::move(onNeedSwarmSocket), std::move(oneToOneRecvCb))} { if (autoLoadConversations) { loadConversations(); } } void ConversationModule::setAccountManager(std::shared_ptr<AccountManager> accountManager) { std::unique_lock lk(pimpl_->conversationsMtx_); pimpl_->accountManager_ = accountManager; } #ifdef LIBJAMI_TESTABLE void ConversationModule::onBootstrapStatus( const std::function<void(std::string, Conversation::BootstrapStatus)>& cb) { pimpl_->bootstrapCbTest_ = cb; for (auto& c : pimpl_->getConversations()) c->onBootstrapStatus(pimpl_->bootstrapCbTest_); } #endif void ConversationModule::loadConversations() { auto acc = pimpl_->account_.lock(); if (!acc) return; JAMI_LOG("[Account {}] Start loading conversations…", pimpl_->accountId_); auto conversationsRepositories = dhtnet::fileutils::readDirectory( fileutils::get_data_dir() / pimpl_->accountId_ / "conversations"); std::unique_lock lk(pimpl_->conversationsMtx_); auto contacts = pimpl_->accountManager_->getContacts(true); // Avoid to lock configurationMtx while conv Mtx is locked std::unique_lock ilk(pimpl_->convInfosMtx_); pimpl_->convInfos_ = convInfos(pimpl_->accountId_); pimpl_->conversations_.clear(); struct Ctx { std::mutex cvMtx; std::condition_variable cv; std::mutex toRmMtx; std::set<std::string> toRm; std::mutex convMtx; size_t convNb; std::vector<std::map<std::string, std::string>> contacts; std::vector<std::tuple<std::string, std::string, std::string>> updateContactConv; }; auto ctx = std::make_shared<Ctx>(); ctx->convNb = conversationsRepositories.size(); ctx->contacts = std::move(contacts); for (auto&& r : conversationsRepositories) { dht::ThreadPool::io().run([this, ctx, repository=std::move(r), acc] { try { auto sconv = std::make_shared<SyncedConversation>(repository); auto conv = std::make_shared<Conversation>(acc, repository); conv->onMessageStatusChanged([this, repository](const auto& status) { auto msg = std::make_shared<SyncMsg>(); msg->ms = {{repository, status}}; pimpl_->needsSyncingCb_(std::move(msg)); }); conv->onMembersChanged( [w = pimpl_->weak_from_this(), repository](const auto& members) { // Delay in another thread to avoid deadlocks dht::ThreadPool::io().run([w, repository, members = std::move(members)] { if (auto sthis = w.lock()) sthis->setConversationMembers(repository, members); }); }); conv->onNeedSocket(pimpl_->onNeedSwarmSocket_); auto members = conv->memberUris(acc->getUsername(), {}); // NOTE: The following if is here to protect against any incorrect state // that can be introduced if (conv->mode() == ConversationMode::ONE_TO_ONE && members.size() == 1) { // If we got a 1:1 conversation, but not in the contact details, it's rather a // duplicate or a weird state auto otherUri = *members.begin(); auto itContact = std::find_if(ctx->contacts.cbegin(), ctx->contacts.cend(), [&](const auto& c) { return c.at("id") == otherUri; }); if (itContact == ctx->contacts.end()) { JAMI_WARNING("Contact {} not found", otherUri); std::lock_guard lkCv {ctx->cvMtx}; --ctx->convNb; ctx->cv.notify_all(); return; } const std::string& convFromDetails = itContact->at("conversationId"); auto removed = std::stoul(itContact->at("removed")); auto added = std::stoul(itContact->at("added")); auto isRemoved = removed > added; if (convFromDetails != repository) { if (convFromDetails.empty()) { if (isRemoved) { // If details is empty, contact is removed and not banned. JAMI_ERROR("Conversation {} detected for {} and should be removed", repository, otherUri); std::lock_guard lkMtx {ctx->toRmMtx}; ctx->toRm.insert(repository); } else { JAMI_ERROR("No conversation detected for {} but one exists ({}). " "Update details", otherUri, repository); std::lock_guard lkMtx {ctx->toRmMtx}; ctx->updateContactConv.emplace_back( std::make_tuple(otherUri, convFromDetails, repository)); } } else { JAMI_ERROR("Multiple conversation detected for {} but ({} & {})", otherUri, repository, convFromDetails); std::lock_guard lkMtx {ctx->toRmMtx}; ctx->toRm.insert(repository); } } } { std::lock_guard lkMtx {ctx->convMtx}; auto convInfo = pimpl_->convInfos_.find(repository); if (convInfo == pimpl_->convInfos_.end()) { JAMI_ERROR("Missing conv info for {}. This is a bug!", repository); sconv->info.created = std::time(nullptr); sconv->info.lastDisplayed = conv->infos()[ConversationMapKeys::LAST_DISPLAYED]; } else { sconv->info = convInfo->second; if (convInfo->second.isRemoved()) { // A conversation was removed, but repository still exists conv->setRemovingFlag(); std::lock_guard lkMtx {ctx->toRmMtx}; ctx->toRm.insert(repository); } } // Even if we found the conversation in convInfos_, unable to assume that the list of members // stored in `convInfo` is correct (https://git.jami.net/savoirfairelinux/jami-daemon/-/issues/1025). // For this reason, we always use the list we got from the conversation repository to set // the value of `sconv->info.members`. members.emplace(acc->getUsername()); sconv->info.members = std::move(members); // convInfosMtx_ is already locked pimpl_->convInfos_[repository] = sconv->info; } auto commits = conv->commitsEndedCalls(); if (!commits.empty()) { // Note: here, this means that some calls were actives while the // daemon finished (can be a crash). // Notify other in the conversation that the call is finished pimpl_->sendMessageNotification(*conv, true, *commits.rbegin()); } sconv->conversation = conv; std::lock_guard lkMtx {ctx->convMtx}; pimpl_->conversations_.emplace(repository, std::move(sconv)); } catch (const std::logic_error& e) { JAMI_WARNING("[Account {}] Conversations not loaded: {}", pimpl_->accountId_, e.what()); } std::lock_guard lkCv {ctx->cvMtx}; --ctx->convNb; ctx->cv.notify_all(); }); } std::unique_lock lkCv(ctx->cvMtx); ctx->cv.wait(lkCv, [&] { return ctx->convNb == 0; }); // Prune any invalid conversations without members and // set the removed flag if needed std::set<std::string> removed; for (auto itInfo = pimpl_->convInfos_.begin(); itInfo != pimpl_->convInfos_.end();) { const auto& info = itInfo->second; if (info.members.empty()) { itInfo = pimpl_->convInfos_.erase(itInfo); continue; } if (info.isRemoved()) removed.insert(info.id); auto itConv = pimpl_->conversations_.find(info.id); if (itConv == pimpl_->conversations_.end()) { // convInfos_ can contain a conversation that is not yet cloned // so we need to add it there. itConv = pimpl_->conversations_ .emplace(info.id, std::make_shared<SyncedConversation>(info)) .first; } if (itConv != pimpl_->conversations_.end() && itConv->second && itConv->second->conversation && info.isRemoved()) itConv->second->conversation->setRemovingFlag(); if (!info.isRemoved() && itConv == pimpl_->conversations_.end()) { // In this case, the conversation is not synced and we only know ourself if (info.members.size() == 1 && *info.members.begin() == acc->getUsername()) { JAMI_WARNING("[Account {:s}] Conversation {:s} seems not present/synced.", pimpl_->accountId_, info.id); emitSignal<libjami::ConversationSignal::ConversationRemoved>(pimpl_->accountId_, info.id); itInfo = pimpl_->convInfos_.erase(itInfo); continue; } } ++itInfo; } // On oldest version, removeConversation didn't update "appdata/contacts" // causing a potential incorrect state between "appdata/contacts" and "appdata/convInfos" if (!removed.empty()) acc->unlinkConversations(removed); // Save if we've removed some invalid entries pimpl_->saveConvInfos(); ilk.unlock(); lk.unlock(); dht::ThreadPool::io().run([w = pimpl_->weak(), acc, updateContactConv = std::move(ctx->updateContactConv), toRm = std::move(ctx->toRm)]() { // Will lock account manager if (auto shared = w.lock()) shared->fixStructures(acc, updateContactConv, toRm); }); } void ConversationModule::loadSingleConversation(const std::string& convId) { auto acc = pimpl_->account_.lock(); if (!acc) return; JAMI_LOG("[Account {}] Start loading conversation {}", pimpl_->accountId_, convId); std::unique_lock lk(pimpl_->conversationsMtx_); std::unique_lock ilk(pimpl_->convInfosMtx_); // Load convInfos to retrieve requests that have been accepted but not yet synchronized. pimpl_->convInfos_ = convInfos(pimpl_->accountId_); pimpl_->conversations_.clear(); try { auto sconv = std::make_shared<SyncedConversation>(convId); auto conv = std::make_shared<Conversation>(acc, convId); conv->onNeedSocket(pimpl_->onNeedSwarmSocket_); sconv->conversation = conv; pimpl_->conversations_.emplace(convId, std::move(sconv)); } catch (const std::logic_error& e) { JAMI_WARNING("[Account {}] Conversations not loaded: {}", pimpl_->accountId_, e.what()); } // Add all other conversations as dummy conversations to indicate their existence so // isConversation could detect conversations correctly. auto conversationsRepositoryIds = dhtnet::fileutils::readDirectory( fileutils::get_data_dir() / pimpl_->accountId_ / "conversations"); for (auto repositoryId : conversationsRepositoryIds) { if (repositoryId != convId) { auto conv = std::make_shared<SyncedConversation>(convId); pimpl_->conversations_.emplace(repositoryId, conv); } } // Add conversations from convInfos_ so isConversation could detect conversations correctly. // This includes conversations that have been accepted but are not yet synchronized. for (auto itInfo = pimpl_->convInfos_.begin(); itInfo != pimpl_->convInfos_.end();) { const auto& info = itInfo->second; if (info.members.empty()) { itInfo = pimpl_->convInfos_.erase(itInfo); continue; } auto itConv = pimpl_->conversations_.find(info.id); if (itConv == pimpl_->conversations_.end()) { // convInfos_ can contain a conversation that is not yet cloned // so we need to add it there. pimpl_->conversations_.emplace(info.id, std::make_shared<SyncedConversation>(info)).first; } ++itInfo; } ilk.unlock(); lk.unlock(); } void ConversationModule::bootstrap(const std::string& convId) { pimpl_->bootstrap(convId); } void ConversationModule::monitor() { for (auto& conv : pimpl_->getConversations()) conv->monitor(); } void ConversationModule::clearPendingFetch() { // Note: This is a workaround. convModule() is kept if account is disabled/re-enabled. // iOS uses setAccountActive() a lot, and if for some reason the previous pending fetch // is not erased (callback not called), it will block the new messages as it will not // sync. The best way to debug this is to get logs from the last ICE connection for // syncing the conversation. It may have been killed in some un-expected way avoiding to // call the callbacks. This should never happen, but if it's the case, this will allow // new messages to be synced correctly. for (auto& conv : pimpl_->getSyncedConversations()) { std::lock_guard lk(conv->mtx); if (conv && conv->pending) { JAMI_ERR("This is a bug, seems to still fetch to some device on initializing"); conv->pending.reset(); } } } void ConversationModule::reloadRequests() { pimpl_->conversationsRequests_ = convRequests(pimpl_->accountId_); } std::vector<std::string> ConversationModule::getConversations() const { std::vector<std::string> result; std::lock_guard lk(pimpl_->convInfosMtx_); result.reserve(pimpl_->convInfos_.size()); for (const auto& [key, conv] : pimpl_->convInfos_) { if (conv.isRemoved()) continue; result.emplace_back(key); } return result; } std::string ConversationModule::getOneToOneConversation(const std::string& uri) const noexcept { return pimpl_->getOneToOneConversation(uri); } bool ConversationModule::updateConvForContact(const std::string& uri, const std::string& oldConv, const std::string& newConv) { return pimpl_->updateConvForContact(uri, oldConv, newConv); } std::vector<std::map<std::string, std::string>> ConversationModule::getConversationRequests() const { std::vector<std::map<std::string, std::string>> requests; std::lock_guard lk(pimpl_->conversationsRequestsMtx_); requests.reserve(pimpl_->conversationsRequests_.size()); for (const auto& [id, request] : pimpl_->conversationsRequests_) { if (request.declined) continue; // Do not add declined requests requests.emplace_back(request.toMap()); } return requests; } void ConversationModule::onTrustRequest(const std::string& uri, const std::string& conversationId, const std::vector<uint8_t>& payload, time_t received) { auto oldConv = getOneToOneConversation(uri); if (!oldConv.empty() && pimpl_->isConversation(oldConv)) { // If there is already an active one to one conversation here, it's an active // contact and the contact will reclone this activeConv, so ignore the request JAMI_WARNING( "Contact is sending a request for a non active conversation. Ignore. They will " "clone the old one"); return; } std::unique_lock lk(pimpl_->conversationsRequestsMtx_); ConversationRequest req; req.from = uri; req.conversationId = conversationId; req.received = std::time(nullptr); req.metadatas = ConversationRepository::infosFromVCard(vCard::utils::toMap( std::string_view(reinterpret_cast<const char*>(payload.data()), payload.size()))); auto reqMap = req.toMap(); if (pimpl_->addConversationRequest(conversationId, std::move(req))) { lk.unlock(); emitSignal<libjami::ConfigurationSignal::IncomingTrustRequest>(pimpl_->accountId_, conversationId, uri, payload, received); emitSignal<libjami::ConversationSignal::ConversationRequestReceived>(pimpl_->accountId_, conversationId, reqMap); pimpl_->needsSyncingCb_({}); } else { JAMI_DEBUG("[Account {}] Received a request for a conversation " "already existing. Ignore", pimpl_->accountId_); } } void ConversationModule::onConversationRequest(const std::string& from, const Json::Value& value) { ConversationRequest req(value); auto isOneToOne = req.isOneToOne(); std::string oldConv; if (isOneToOne) { oldConv = pimpl_->getOneToOneConversation(from); } std::unique_lock lk(pimpl_->conversationsRequestsMtx_); JAMI_DEBUG("[Account {}] Receive a new conversation request for conversation {} from {}", pimpl_->accountId_, req.conversationId, from); auto convId = req.conversationId; // Already accepted request, do nothing if (pimpl_->isConversation(convId)) return; auto oldReq = pimpl_->getRequest(convId); if (oldReq != std::nullopt) { JAMI_DEBUG("[Account {}] Received a request for a conversation already existing. " "Ignore. Declined: {}", pimpl_->accountId_, static_cast<int>(oldReq->declined)); return; } if (!oldConv.empty()) { lk.unlock(); // Already a conversation with the contact. // If there is already an active one to one conversation here, it's an active // contact and the contact will reclone this activeConv, so ignore the request JAMI_WARNING( "Contact is sending a request for a non active conversation. Ignore. They will " "clone the old one"); return; } req.received = std::time(nullptr); req.from = from; auto reqMap = req.toMap(); if (pimpl_->addConversationRequest(convId, std::move(req))) { lk.unlock(); // Note: no need to sync here because other connected devices should receive // the same conversation request. Will sync when the conversation will be added if (isOneToOne) pimpl_->oneToOneRecvCb_(convId, from); emitSignal<libjami::ConversationSignal::ConversationRequestReceived>(pimpl_->accountId_, convId, reqMap); } } std::string ConversationModule::peerFromConversationRequest(const std::string& convId) const { std::lock_guard lk(pimpl_->conversationsRequestsMtx_); auto it = pimpl_->conversationsRequests_.find(convId); if (it != pimpl_->conversationsRequests_.end()) { return it->second.from; } return {}; } void ConversationModule::onNeedConversationRequest(const std::string& from, const std::string& conversationId) { pimpl_->withConversation(conversationId, [&](auto& conversation) { if (!conversation.isMember(from, true)) { JAMI_WARNING("{} is asking a new invite for {}, but not a member", from, conversationId); return; } JAMI_LOG("{} is asking a new invite for {}", from, conversationId); pimpl_->sendMsgCb_(from, {}, conversation.generateInvitation(), 0); }); } void ConversationModule::acceptConversationRequest(const std::string& conversationId, const std::string& deviceId) { // For all conversation members, try to open a git channel with this conversation ID std::unique_lock lkCr(pimpl_->conversationsRequestsMtx_); auto request = pimpl_->getRequest(conversationId); if (request == std::nullopt) { lkCr.unlock(); if (auto conv = pimpl_->getConversation(conversationId)) { std::unique_lock lk(conv->mtx); if (!conv->conversation) { lk.unlock(); pimpl_->cloneConversationFrom(conv, deviceId); } } JAMI_WARNING("[Account {}] Request not found for conversation {}", pimpl_->accountId_, conversationId); return; } pimpl_->rmConversationRequest(conversationId); lkCr.unlock(); pimpl_->accountManager_->acceptTrustRequest(request->from, true); cloneConversationFrom(conversationId, request->from); } void ConversationModule::declineConversationRequest(const std::string& conversationId) { std::lock_guard lk(pimpl_->conversationsRequestsMtx_); auto it = pimpl_->conversationsRequests_.find(conversationId); if (it != pimpl_->conversationsRequests_.end()) { it->second.declined = std::time(nullptr); pimpl_->saveConvRequests(); } pimpl_->syncingMetadatas_.erase(conversationId); pimpl_->saveMetadatas(); emitSignal<libjami::ConversationSignal::ConversationRequestDeclined>(pimpl_->accountId_, conversationId); pimpl_->needsSyncingCb_({}); } std::string ConversationModule::startConversation(ConversationMode mode, const dht::InfoHash& otherMember) { auto acc = pimpl_->account_.lock(); if (!acc) return {}; std::vector<DeviceId> kd; for (const auto& [id, _] : acc->getKnownDevices()) kd.emplace_back(id); // Create the conversation object std::shared_ptr<Conversation> conversation; try { conversation = std::make_shared<Conversation>(acc, mode, otherMember.toString()); auto conversationId = conversation->id(); conversation->onMessageStatusChanged([this, conversationId](const auto& status) { auto msg = std::make_shared<SyncMsg>(); msg->ms = {{conversationId, status}}; pimpl_->needsSyncingCb_(std::move(msg)); }); conversation->onMembersChanged([w=pimpl_->weak_from_this(), conversationId](const auto& members) { // Delay in another thread to avoid deadlocks dht::ThreadPool::io().run([w, conversationId, members = std::move(members)] { if (auto sthis = w.lock()) sthis->setConversationMembers(conversationId, members); }); }); conversation->onNeedSocket(pimpl_->onNeedSwarmSocket_); #ifdef LIBJAMI_TESTABLE conversation->onBootstrapStatus(pimpl_->bootstrapCbTest_); #endif // LIBJAMI_TESTABLE conversation->bootstrap(std::bind(&ConversationModule::Impl::bootstrapCb, pimpl_.get(), conversationId), kd); } catch (const std::exception& e) { JAMI_ERROR("[Account {}] Error while generating a conversation {}", pimpl_->accountId_, e.what()); return {}; } auto convId = conversation->id(); auto conv = pimpl_->startConversation(convId); std::unique_lock lk(conv->mtx); conv->info.created = std::time(nullptr); conv->info.members.emplace(pimpl_->username_); if (otherMember) conv->info.members.emplace(otherMember.toString()); conv->conversation = conversation; addConvInfo(conv->info); lk.unlock(); pimpl_->needsSyncingCb_({}); emitSignal<libjami::ConversationSignal::ConversationReady>(pimpl_->accountId_, convId); return convId; } void ConversationModule::cloneConversationFrom(const std::string& conversationId, const std::string& uri, const std::string& oldConvId) { pimpl_->cloneConversationFrom(conversationId, uri, oldConvId); } // Message send/load void ConversationModule::sendMessage(const std::string& conversationId, std::string message, const std::string& replyTo, const std::string& type, bool announce, OnCommitCb&& onCommit, OnDoneCb&& cb) { pimpl_->sendMessage(conversationId, std::move(message), replyTo, type, announce, std::move(onCommit), std::move(cb)); } void ConversationModule::sendMessage(const std::string& conversationId, Json::Value&& value, const std::string& replyTo, bool announce, OnCommitCb&& onCommit, OnDoneCb&& cb) { pimpl_->sendMessage(conversationId, std::move(value), replyTo, announce, std::move(onCommit), std::move(cb)); } void ConversationModule::editMessage(const std::string& conversationId, const std::string& newBody, const std::string& editedId) { pimpl_->editMessage(conversationId, newBody, editedId); } void ConversationModule::reactToMessage(const std::string& conversationId, const std::string& newBody, const std::string& reactToId) { // Commit message edition Json::Value json; json["body"] = newBody; json["react-to"] = reactToId; json["type"] = "text/plain"; pimpl_->sendMessage(conversationId, std::move(json)); } void ConversationModule::addCallHistoryMessage(const std::string& uri, uint64_t duration_ms, const std::string& reason) { auto finalUri = uri.substr(0, uri.find("@ring.dht")); finalUri = finalUri.substr(0, uri.find("@jami.dht")); auto convId = getOneToOneConversation(finalUri); if (!convId.empty()) { Json::Value value; value["to"] = finalUri; value["type"] = "application/call-history+json"; value["duration"] = std::to_string(duration_ms); if (!reason.empty()) value["reason"] = reason; sendMessage(convId, std::move(value)); } } bool ConversationModule::onMessageDisplayed(const std::string& peer, const std::string& conversationId, const std::string& interactionId) { if (auto conv = pimpl_->getConversation(conversationId)) { std::unique_lock lk(conv->mtx); if (auto conversation = conv->conversation) { lk.unlock(); return conversation->setMessageDisplayed(peer, interactionId); } } return false; } std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> ConversationModule::convMessageStatus() const { std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> messageStatus; for (const auto& conv : pimpl_->getConversations()) { auto d = conv->messageStatus(); if (!d.empty()) messageStatus[conv->id()] = std::move(d); } return messageStatus; } uint32_t ConversationModule::loadConversationMessages(const std::string& conversationId, const std::string& fromMessage, size_t n) { auto acc = pimpl_->account_.lock(); if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { const uint32_t id = std::uniform_int_distribution<uint32_t> {}(acc->rand); LogOptions options; options.from = fromMessage; options.nbOfCommits = n; conv->conversation->loadMessages( [accountId = pimpl_->accountId_, conversationId, id](auto&& messages) { emitSignal<libjami::ConversationSignal::ConversationLoaded>(id, accountId, conversationId, messages); }, options); return id; } } return 0; } void ConversationModule::clearCache(const std::string& conversationId) { if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { conv->conversation->clearCache(); } } } uint32_t ConversationModule::loadConversation(const std::string& conversationId, const std::string& fromMessage, size_t n) { auto acc = pimpl_->account_.lock(); if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { const uint32_t id = std::uniform_int_distribution<uint32_t> {}(acc->rand); LogOptions options; options.from = fromMessage; options.nbOfCommits = n; conv->conversation->loadMessages2( [accountId = pimpl_->accountId_, conversationId, id](auto&& messages) { emitSignal<libjami::ConversationSignal::SwarmLoaded>(id, accountId, conversationId, messages); }, options); return id; } } return 0; } uint32_t ConversationModule::loadConversationUntil(const std::string& conversationId, const std::string& fromMessage, const std::string& toMessage) { auto acc = pimpl_->account_.lock(); if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { const uint32_t id = std::uniform_int_distribution<uint32_t> {}(acc->rand); LogOptions options; options.from = fromMessage; options.to = toMessage; options.includeTo = true; conv->conversation->loadMessages( [accountId = pimpl_->accountId_, conversationId, id](auto&& messages) { emitSignal<libjami::ConversationSignal::ConversationLoaded>(id, accountId, conversationId, messages); }, options); return id; } } return 0; } uint32_t ConversationModule::loadSwarmUntil(const std::string& conversationId, const std::string& fromMessage, const std::string& toMessage) { auto acc = pimpl_->account_.lock(); if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { const uint32_t id = std::uniform_int_distribution<uint32_t> {}(acc->rand); LogOptions options; options.from = fromMessage; options.to = toMessage; options.includeTo = true; conv->conversation->loadMessages2( [accountId = pimpl_->accountId_, conversationId, id](auto&& messages) { emitSignal<libjami::ConversationSignal::SwarmLoaded>(id, accountId, conversationId, messages); }, options); return id; } } return 0; } std::shared_ptr<TransferManager> ConversationModule::dataTransfer(const std::string& conversationId) const { return pimpl_->withConversation(conversationId, [](auto& conversation) { return conversation.dataTransfer(); }); } bool ConversationModule::onFileChannelRequest(const std::string& conversationId, const std::string& member, const std::string& fileId, bool verifyShaSum) const { if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->onFileChannelRequest(member, fileId, verifyShaSum); } return false; } bool ConversationModule::downloadFile(const std::string& conversationId, const std::string& interactionId, const std::string& fileId, const std::string& path, size_t start, size_t end) { if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->downloadFile(interactionId, fileId, path, "", "", start, end); } return false; } void ConversationModule::syncConversations(const std::string& peer, const std::string& deviceId) { // Sync conversations where peer is member std::set<std::string> toFetch; std::set<std::string> toClone; for (const auto& conv : pimpl_->getSyncedConversations()) { std::lock_guard lk(conv->mtx); if (conv->conversation) { if (!conv->conversation->isRemoving() && conv->conversation->isMember(peer, false)) { toFetch.emplace(conv->info.id); } } else if (!conv->info.isRemoved() && std::find(conv->info.members.begin(), conv->info.members.end(), peer) != conv->info.members.end()) { // In this case the conversation was never cloned (can be after an import) toClone.emplace(conv->info.id); } } for (const auto& cid : toFetch) pimpl_->fetchNewCommits(peer, deviceId, cid); for (const auto& cid : toClone) pimpl_->cloneConversation(deviceId, peer, cid); if (pimpl_->syncCnt.load() == 0) emitSignal<libjami::ConversationSignal::ConversationSyncFinished>(pimpl_->accountId_); } void ConversationModule::onSyncData(const SyncMsg& msg, const std::string& peerId, const std::string& deviceId) { std::vector<std::string> toClone; for (const auto& [key, convInfo] : msg.c) { const auto& convId = convInfo.id; { std::lock_guard lk(pimpl_->conversationsRequestsMtx_); pimpl_->rmConversationRequest(convId); } auto conv = pimpl_->startConversation(convInfo); std::unique_lock lk(conv->mtx); // Skip outdated info if (std::max(convInfo.created, convInfo.removed) < std::max(conv->info.created, conv->info.removed)) continue; if (not convInfo.isRemoved()) { // If multi devices, it can detect a conversation that was already // removed, so just check if the convinfo contains a removed conv if (conv->info.removed) { if (conv->info.removed >= convInfo.created) { // Only reclone if re-added, else the peer is not synced yet (could be // offline before) continue; } JAMI_DEBUG("Re-add previously removed conversation {:s}", convId); } conv->info = convInfo; if (!conv->conversation) { if (deviceId != "") { pimpl_->cloneConversation(deviceId, peerId, conv); } else { // In this case, information is from JAMS // JAMS does not store the conversation itself, so we // must use information to clone the conversation addConvInfo(convInfo); toClone.emplace_back(convId); } } } else { if (conv->conversation && !conv->conversation->isRemoving()) { emitSignal<libjami::ConversationSignal::ConversationRemoved>(pimpl_->accountId_, convId); conv->conversation->setRemovingFlag(); } auto update = false; if (!conv->info.removed) { update = true; conv->info.removed = std::time(nullptr); } if (convInfo.erased && !conv->info.erased) { conv->info.erased = std::time(nullptr); pimpl_->addConvInfo(conv->info); pimpl_->removeRepositoryImpl(*conv, false); } else if (update) { pimpl_->addConvInfo(conv->info); } } } for (const auto& cid : toClone) { auto members = getConversationMembers(cid); for (const auto& member : members) { if (member.at("uri") != pimpl_->username_) cloneConversationFrom(cid, member.at("uri")); } } for (const auto& [convId, req] : msg.cr) { if (req.from == pimpl_->username_) { JAMI_WARNING("Detected request from ourself, ignore {}.", convId); continue; } std::unique_lock lk(pimpl_->conversationsRequestsMtx_); if (pimpl_->isConversation(convId)) { // Already handled request pimpl_->rmConversationRequest(convId); continue; } // New request if (!pimpl_->addConversationRequest(convId, req)) continue; lk.unlock(); if (req.declined != 0) { // Request declined JAMI_LOG("[Account {:s}] Declined request detected for conversation {:s} (device {:s})", pimpl_->accountId_, convId, deviceId); pimpl_->syncingMetadatas_.erase(convId); pimpl_->saveMetadatas(); emitSignal<libjami::ConversationSignal::ConversationRequestDeclined>(pimpl_->accountId_, convId); continue; } JAMI_LOG("[Account {:s}] New request detected for conversation {:s} (device {:s})", pimpl_->accountId_, convId, deviceId); emitSignal<libjami::ConversationSignal::ConversationRequestReceived>(pimpl_->accountId_, convId, req.toMap()); } // Updates preferences for conversations for (const auto& [convId, p] : msg.p) { if (auto conv = pimpl_->getConversation(convId)) { std::unique_lock lk(conv->mtx); if (conv->conversation) { auto conversation = conv->conversation; lk.unlock(); conversation->updatePreferences(p); } else if (conv->pending) { conv->pending->preferences = p; } } } // Updates displayed for conversations for (const auto& [convId, ms] : msg.ms) { if (auto conv = pimpl_->getConversation(convId)) { std::unique_lock lk(conv->mtx); if (conv->conversation) { auto conversation = conv->conversation; lk.unlock(); conversation->updateMessageStatus(ms); } else if (conv->pending) { conv->pending->status = ms; } } } } bool ConversationModule::needsSyncingWith(const std::string& memberUri, const std::string& deviceId) const { // Check if a conversation needs to fetch remote or to be cloned std::lock_guard lk(pimpl_->conversationsMtx_); for (const auto& [key, ci] : pimpl_->conversations_) { std::lock_guard lk(ci->mtx); if (ci->conversation) { if (ci->conversation->isRemoving() && ci->conversation->isMember(memberUri, false)) return true; } else if (!ci->info.removed && std::find(ci->info.members.begin(), ci->info.members.end(), memberUri) != ci->info.members.end()) { // In this case the conversation was never cloned (can be after an import) return true; } } return false; } void ConversationModule::setFetched(const std::string& conversationId, const std::string& deviceId, const std::string& commitId) { if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { bool remove = conv->conversation->isRemoving(); conv->conversation->hasFetched(deviceId, commitId); if (remove) pimpl_->removeRepositoryImpl(*conv, true); } } } void ConversationModule::fetchNewCommits(const std::string& peer, const std::string& deviceId, const std::string& conversationId, const std::string& commitId) { pimpl_->fetchNewCommits(peer, deviceId, conversationId, commitId); } void ConversationModule::addConversationMember(const std::string& conversationId, const dht::InfoHash& contactUri, bool sendRequest) { auto conv = pimpl_->getConversation(conversationId); if (not conv || not conv->conversation) { JAMI_ERROR("Conversation {:s} does not exist", conversationId); return; } std::unique_lock lk(conv->mtx); auto contactUriStr = contactUri.toString(); if (conv->conversation->isMember(contactUriStr, true)) { JAMI_DEBUG("{:s} is already a member of {:s}, resend invite", contactUriStr, conversationId); // Note: This should not be necessary, but if for whatever reason the other side didn't // join we should not forbid new invites auto invite = conv->conversation->generateInvitation(); lk.unlock(); pimpl_->sendMsgCb_(contactUriStr, {}, std::move(invite), 0); return; } conv->conversation->addMember( contactUriStr, [this, conv, conversationId, sendRequest, contactUriStr](bool ok, const std::string& commitId) { if (ok) { std::unique_lock lk(conv->mtx); pimpl_->sendMessageNotification(*conv->conversation, true, commitId); // For the other members if (sendRequest) { auto invite = conv->conversation->generateInvitation(); lk.unlock(); pimpl_->sendMsgCb_(contactUriStr, {}, std::move(invite), 0); } } }); } void ConversationModule::removeConversationMember(const std::string& conversationId, const dht::InfoHash& contactUri, bool isDevice) { auto contactUriStr = contactUri.toString(); if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->removeMember( contactUriStr, isDevice, [this, conversationId](bool ok, const std::string& commitId) { if (ok) { pimpl_->sendMessageNotification(conversationId, true, commitId); } }); } } std::vector<std::map<std::string, std::string>> ConversationModule::getConversationMembers(const std::string& conversationId, bool includeBanned) const { return pimpl_->getConversationMembers(conversationId, includeBanned); } uint32_t ConversationModule::countInteractions(const std::string& convId, const std::string& toId, const std::string& fromId, const std::string& authorUri) const { if (auto conv = pimpl_->getConversation(convId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->countInteractions(toId, fromId, authorUri); } return 0; } void ConversationModule::search(uint32_t req, const std::string& convId, const Filter& filter) const { if (convId.empty()) { auto convs = pimpl_->getConversations(); if (convs.empty()) { emitSignal<libjami::ConversationSignal::MessagesFound>( req, pimpl_->accountId_, std::string {}, std::vector<std::map<std::string, std::string>> {}); return; } auto finishedFlag = std::make_shared<std::atomic_int>(convs.size()); for (const auto& conv : convs) { conv->search(req, filter, finishedFlag); } } else if (auto conv = pimpl_->getConversation(convId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) conv->conversation->search(req, filter, std::make_shared<std::atomic_int>(1)); } } void ConversationModule::updateConversationInfos(const std::string& conversationId, const std::map<std::string, std::string>& infos, bool sync) { auto conv = pimpl_->getConversation(conversationId); if (not conv or not conv->conversation) { JAMI_ERROR("Conversation {:s} does not exist", conversationId); return; } std::lock_guard lk(conv->mtx); conv->conversation ->updateInfos(infos, [this, conversationId, sync](bool ok, const std::string& commitId) { if (ok && sync) { pimpl_->sendMessageNotification(conversationId, true, commitId); } else if (sync) JAMI_WARNING("Unable to update info on {:s}", conversationId); }); } std::map<std::string, std::string> ConversationModule::conversationInfos(const std::string& conversationId) const { { std::lock_guard lk(pimpl_->conversationsRequestsMtx_); auto itReq = pimpl_->conversationsRequests_.find(conversationId); if (itReq != pimpl_->conversationsRequests_.end()) return itReq->second.metadatas; } if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); std::map<std::string, std::string> md; { auto syncingMetadatasIt = pimpl_->syncingMetadatas_.find(conversationId); if (syncingMetadatasIt != pimpl_->syncingMetadatas_.end()) { if (conv->conversation) { pimpl_->syncingMetadatas_.erase(syncingMetadatasIt); pimpl_->saveMetadatas(); } else { md = syncingMetadatasIt->second; } } } if (conv->conversation) return conv->conversation->infos(); else return md; } JAMI_ERROR("Conversation {:s} does not exist", conversationId); return {}; } void ConversationModule::setConversationPreferences(const std::string& conversationId, const std::map<std::string, std::string>& prefs) { if (auto conv = pimpl_->getConversation(conversationId)) { std::unique_lock lk(conv->mtx); if (not conv->conversation) { JAMI_ERROR("Conversation {:s} does not exist", conversationId); return; } auto conversation = conv->conversation; lk.unlock(); conversation->updatePreferences(prefs); auto msg = std::make_shared<SyncMsg>(); msg->p = {{conversationId, conversation->preferences(true)}}; pimpl_->needsSyncingCb_(std::move(msg)); } } std::map<std::string, std::string> ConversationModule::getConversationPreferences(const std::string& conversationId, bool includeCreated) const { if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->preferences(includeCreated); } return {}; } std::map<std::string, std::map<std::string, std::string>> ConversationModule::convPreferences() const { std::map<std::string, std::map<std::string, std::string>> p; for (const auto& conv : pimpl_->getConversations()) { auto prefs = conv->preferences(true); if (!prefs.empty()) p[conv->id()] = std::move(prefs); } return p; } std::vector<uint8_t> ConversationModule::conversationVCard(const std::string& conversationId) const { if (auto conv = pimpl_->getConversation(conversationId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->vCard(); } JAMI_ERROR("Conversation {:s} does not exist", conversationId); return {}; } bool ConversationModule::isBanned(const std::string& convId, const std::string& uri) const { if (auto conv = pimpl_->getConversation(convId)) { std::lock_guard lk(conv->mtx); if (!conv->conversation) return true; if (conv->conversation->mode() != ConversationMode::ONE_TO_ONE) return conv->conversation->isBanned(uri); } // If 1:1 we check the certificate status std::lock_guard lk(pimpl_->conversationsMtx_); return pimpl_->accountManager_->getCertificateStatus(uri) == dhtnet::tls::TrustStore::PermissionStatus::BANNED; } void ConversationModule::removeContact(const std::string& uri, bool banned) { // Remove linked conversation's requests { std::lock_guard lk(pimpl_->conversationsRequestsMtx_); auto update = false; for (auto it = pimpl_->conversationsRequests_.begin(); it != pimpl_->conversationsRequests_.end(); ++it) { if (it->second.from == uri && !it->second.declined) { JAMI_DEBUG("Declining conversation request {:s} from {:s}", it->first, uri); pimpl_->syncingMetadatas_.erase(it->first); pimpl_->saveMetadatas(); emitSignal<libjami::ConversationSignal::ConversationRequestDeclined>( pimpl_->accountId_, it->first); update = true; it->second.declined = std::time(nullptr); } } if (update) { pimpl_->saveConvRequests(); pimpl_->needsSyncingCb_({}); } } if (banned) { auto conversationId = getOneToOneConversation(uri); pimpl_->withConversation(conversationId, [&](auto& conv) { conv.shutdownConnections(); }); return; // Keep the conversation in banned model but stop connections } // Remove related conversation auto isSelf = uri == pimpl_->username_; std::vector<std::string> toRm; auto updateClient = [&](const auto& convId) { pimpl_->updateConvForContact(uri, convId, ""); emitSignal<libjami::ConversationSignal::ConversationRemoved>(pimpl_->accountId_, convId); }; auto removeConvInfo = [&](const auto& conv, const auto& members) { if ((isSelf && members.size() == 1) || (!isSelf && std::find(members.begin(), members.end(), uri) != members.end())) { // Mark the conversation as removed if it wasn't already if (!conv->info.isRemoved()) { conv->info.removed = std::time(nullptr); updateClient(conv->info.id); pimpl_->addConvInfo(conv->info); return true; } } return false; }; { std::lock_guard lk(pimpl_->conversationsMtx_); for (auto& [convId, conv] : pimpl_->conversations_) { std::lock_guard lk(conv->mtx); if (conv->conversation) { try { // Note it's important to check getUsername(), else // removing self can remove all conversations if (conv->conversation->mode() == ConversationMode::ONE_TO_ONE) { auto initMembers = conv->conversation->getInitialMembers(); if (removeConvInfo(conv, initMembers)) toRm.emplace_back(convId); } } catch (const std::exception& e) { JAMI_WARN("%s", e.what()); } } else { removeConvInfo(conv, conv->info.members); } } } // Note, if we ban the device, we don't send the leave cause the other peer will just // never got the notifications, so just erase the datas for (const auto& id : toRm) pimpl_->removeRepository(id, true, true); } bool ConversationModule::removeConversation(const std::string& conversationId) { return pimpl_->removeConversation(conversationId); } void ConversationModule::initReplay(const std::string& oldConvId, const std::string& newConvId) { if (auto conv = pimpl_->getConversation(oldConvId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) { std::promise<bool> waitLoad; std::future<bool> fut = waitLoad.get_future(); // we should wait for loadMessage, because it will be deleted after this. conv->conversation->loadMessages( [&](auto&& messages) { std::reverse(messages.begin(), messages.end()); // Log is inverted as we want to replay std::lock_guard lk(pimpl_->replayMtx_); pimpl_->replay_[newConvId] = std::move(messages); waitLoad.set_value(true); }, {}); fut.wait(); } } } bool ConversationModule::isHosting(const std::string& conversationId, const std::string& confId) const { if (conversationId.empty()) { std::lock_guard lk(pimpl_->conversationsMtx_); return std::find_if(pimpl_->conversations_.cbegin(), pimpl_->conversations_.cend(), [&](const auto& conv) { return conv.second->conversation && conv.second->conversation->isHosting(confId); }) != pimpl_->conversations_.cend(); } else if (auto conv = pimpl_->getConversation(conversationId)) { if (conv->conversation) { return conv->conversation->isHosting(confId); } } return false; } std::vector<std::map<std::string, std::string>> ConversationModule::getActiveCalls(const std::string& conversationId) const { return pimpl_->withConversation(conversationId, [](const auto& conversation) { return conversation.currentCalls(); }); } std::shared_ptr<SIPCall> ConversationModule::call(const std::string& url, const std::vector<libjami::MediaMap>& mediaList, std::function<void(const std::string&, const DeviceId&, const std::shared_ptr<SIPCall>&)>&& cb) { std::string conversationId = "", confId = "", uri = "", deviceId = ""; if (url.find('/') == std::string::npos) { conversationId = url; } else { auto parameters = jami::split_string(url, '/'); if (parameters.size() != 4) { JAMI_ERROR("Incorrect url {:s}", url); return {}; } conversationId = parameters[0]; uri = parameters[1]; deviceId = parameters[2]; confId = parameters[3]; } auto conv = pimpl_->getConversation(conversationId); if (!conv) return {}; std::unique_lock lk(conv->mtx); if (!conv->conversation) { JAMI_ERROR("Conversation {:s} not found", conversationId); return {}; } // Check if we want to join a specific conference // So, if confId is specified or if there is some activeCalls // or if we are the default host. auto activeCalls = conv->conversation->currentCalls(); auto infos = conv->conversation->infos(); auto itRdvAccount = infos.find("rdvAccount"); auto itRdvDevice = infos.find("rdvDevice"); auto sendCallRequest = false; if (!confId.empty()) { sendCallRequest = true; JAMI_DEBUG("Calling self, join conference"); } else if (!activeCalls.empty()) { // Else, we try to join active calls sendCallRequest = true; auto& ac = *activeCalls.rbegin(); confId = ac.at("id"); uri = ac.at("uri"); deviceId = ac.at("device"); } else if (itRdvAccount != infos.end() && itRdvDevice != infos.end() && !itRdvAccount->second.empty()) { // Else, creates "to" (accountId/deviceId/conversationId/confId) and ask remote host sendCallRequest = true; uri = itRdvAccount->second; deviceId = itRdvDevice->second; confId = "0"; JAMI_DEBUG("Remote host detected. Calling {:s} on device {:s}", uri, deviceId); } lk.unlock(); auto account = pimpl_->account_.lock(); std::vector<libjami::MediaMap> mediaMap = mediaList.empty() ? MediaAttribute::mediaAttributesToMediaMaps( pimpl_->account_.lock()->createDefaultMediaList( pimpl_->account_.lock()->isVideoEnabled())) : mediaList; if (!sendCallRequest || (uri == pimpl_->username_ && deviceId == pimpl_->deviceId_)) { confId = confId == "0" ? Manager::instance().callFactory.getNewCallID() : confId; // TODO attach host with media list hostConference(conversationId, confId, "", mediaMap); return {}; } // Else we need to create a call auto& manager = Manager::instance(); std::shared_ptr<SIPCall> call = manager.callFactory.newSipCall(account, Call::CallType::OUTGOING, mediaMap); if (not call) return {}; auto callUri = fmt::format("{}/{}/{}/{}", conversationId, uri, deviceId, confId); account->getIceOptions([call, accountId = account->getAccountID(), callUri, uri = std::move(uri), conversationId, deviceId, cb=std::move(cb)](auto&& opts) { if (call->isIceEnabled()) { if (not call->createIceMediaTransport(false) or not call->initIceMediaTransport(true, std::forward<dhtnet::IceTransportOptions>(opts))) { return; } } JAMI_DEBUG("New outgoing call with {}", uri); call->setPeerNumber(uri); call->setPeerUri("swarm:" + uri); JAMI_DEBUG("Calling: {:s}", callUri); call->setState(Call::ConnectionState::TRYING); call->setPeerNumber(callUri); call->setPeerUri("rdv:" + callUri); call->addStateListener([accountId, conversationId](Call::CallState call_state, Call::ConnectionState cnx_state, int) { if (cnx_state == Call::ConnectionState::DISCONNECTED && call_state == Call::CallState::MERROR) { emitSignal<libjami::ConfigurationSignal::NeedsHost>(accountId, conversationId); return true; } return true; }); cb(callUri, DeviceId(deviceId), call); }); return call; } void ConversationModule::hostConference(const std::string& conversationId, const std::string& confId, const std::string& callId, const std::vector<libjami::MediaMap>& mediaList) { auto acc = pimpl_->account_.lock(); if (!acc) return; auto conf = acc->getConference(confId); auto createConf = !conf; std::shared_ptr<SIPCall> call; if (!callId.empty()) { call = std::dynamic_pointer_cast<SIPCall>(acc->getCall(callId)); if (!call) { JAMI_WARNING("No call with id {} found", callId); return; } } if (createConf) { conf = std::make_shared<Conference>(acc, confId); acc->attach(conf); } if (!callId.empty()) conf->addSubCall(callId); if (callId.empty()) conf->attachHost(mediaList); if (createConf) { emitSignal<libjami::CallSignal::ConferenceCreated>(acc->getAccountID(), conversationId, conf->getConfId()); } else { conf->reportMediaNegotiationStatus(); emitSignal<libjami::CallSignal::ConferenceChanged>(acc->getAccountID(), conf->getConfId(), conf->getStateStr()); return; } auto conv = pimpl_->getConversation(conversationId); if (!conv) return; std::unique_lock lk(conv->mtx); if (!conv->conversation) { JAMI_ERROR("Conversation {} not found", conversationId); return; } // Add commit to conversation Json::Value value; value["uri"] = pimpl_->username_; value["device"] = pimpl_->deviceId_; value["confId"] = conf->getConfId(); value["type"] = "application/call-history+json"; conv->conversation->hostConference(std::move(value), [w = pimpl_->weak(), conversationId](bool ok, const std::string& commitId) { if (ok) { if (auto shared = w.lock()) shared->sendMessageNotification(conversationId, true, commitId); } else { JAMI_ERR("Failed to send message to conversation %s", conversationId.c_str()); } }); // When conf finished = remove host & commit // Master call, so when it's stopped, the conference will be stopped (as we use the hold // state for detaching the call) conf->onShutdown( [w = pimpl_->weak(), accountUri = pimpl_->username_, confId=conf->getConfId(), conversationId, conv]( int duration) { auto shared = w.lock(); if (shared) { Json::Value value; value["uri"] = accountUri; value["device"] = shared->deviceId_; value["confId"] = confId; value["type"] = "application/call-history+json"; value["duration"] = std::to_string(duration); std::lock_guard lk(conv->mtx); if (!conv->conversation) { JAMI_ERROR("Conversation {} not found", conversationId); return; } conv->conversation->removeActiveConference( std::move(value), [w, conversationId](bool ok, const std::string& commitId) { if (ok) { if (auto shared = w.lock()) { shared->sendMessageNotification(conversationId, true, commitId); } } else { JAMI_ERROR("Failed to send message to conversation {}", conversationId); } }); } }); } std::map<std::string, ConvInfo> ConversationModule::convInfos(const std::string& accountId) { return convInfosFromPath(fileutils::get_data_dir() / accountId); } std::map<std::string, ConvInfo> ConversationModule::convInfosFromPath(const std::filesystem::path& path) { std::map<std::string, ConvInfo> convInfos; try { // read file std::lock_guard lock(dhtnet::fileutils::getFileLock(path / "convInfo")); auto file = fileutils::loadFile("convInfo", path); // load values msgpack::unpacked result; msgpack::unpack(result, (const char*) file.data(), file.size()); result.get().convert(convInfos); } catch (const std::exception& e) { JAMI_WARN("[convInfo] error loading convInfo: %s", e.what()); } return convInfos; } std::map<std::string, ConversationRequest> ConversationModule::convRequests(const std::string& accountId) { auto path = fileutils::get_data_dir() / accountId; return convRequestsFromPath(path.string()); } std::map<std::string, ConversationRequest> ConversationModule::convRequestsFromPath(const std::filesystem::path& path) { std::map<std::string, ConversationRequest> convRequests; try { // read file std::lock_guard lock(dhtnet::fileutils::getFileLock(path / "convRequests")); auto file = fileutils::loadFile("convRequests", path); // load values msgpack::unpacked result; msgpack::unpack(result, (const char*) file.data(), file.size(), 0); result.get().convert(convRequests); } catch (const std::exception& e) { JAMI_WARN("[convInfo] error loading convInfo: %s", e.what()); } return convRequests; } void ConversationModule::addConvInfo(const ConvInfo& info) { pimpl_->addConvInfo(info); } void ConversationModule::Impl::setConversationMembers(const std::string& convId, const std::set<std::string>& members) { if (auto conv = getConversation(convId)) { std::lock_guard lk(conv->mtx); conv->info.members = members; addConvInfo(conv->info); } } std::shared_ptr<Conversation> ConversationModule::getConversation(const std::string& convId) { if (auto conv = pimpl_->getConversation(convId)) { std::lock_guard lk(conv->mtx); return conv->conversation; } return nullptr; } std::shared_ptr<dhtnet::ChannelSocket> ConversationModule::gitSocket(std::string_view deviceId, std::string_view convId) const { if (auto conv = pimpl_->getConversation(convId)) { std::lock_guard lk(conv->mtx); if (conv->conversation) return conv->conversation->gitSocket(DeviceId(deviceId)); else if (conv->pending) return conv->pending->socket; } return nullptr; } void ConversationModule::addGitSocket(std::string_view deviceId, std::string_view convId, const std::shared_ptr<dhtnet::ChannelSocket>& channel) { if (auto conv = pimpl_->getConversation(convId)) { std::lock_guard lk(conv->mtx); conv->conversation->addGitSocket(DeviceId(deviceId), channel); } else JAMI_WARNING("addGitSocket: Unable to find conversation {:s}", convId); } void ConversationModule::removeGitSocket(std::string_view deviceId, std::string_view convId) { pimpl_->withConversation(convId, [&](auto& conv) { conv.removeGitSocket(DeviceId(deviceId)); }); } void ConversationModule::shutdownConnections() { for (const auto& c : pimpl_->getSyncedConversations()) { std::lock_guard lkc(c->mtx); if (c->conversation) c->conversation->shutdownConnections(); if (c->pending) c->pending->socket = {}; } } void ConversationModule::addSwarmChannel(const std::string& conversationId, std::shared_ptr<dhtnet::ChannelSocket> channel) { pimpl_->withConversation(conversationId, [&](auto& conv) { conv.addSwarmChannel(std::move(channel)); }); } void ConversationModule::connectivityChanged() { for (const auto& conv : pimpl_->getConversations()) conv->connectivityChanged(); } std::shared_ptr<Typers> ConversationModule::getTypers(const std::string& convId) { if (auto c = pimpl_->getConversation(convId)) { std::lock_guard lk(c->mtx); if (c->conversation) return c->conversation->typers(); } return nullptr; } } // namespace jami
132,626
C++
.cpp
3,087
30.521542
160
0.552412
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,796
conversation_channel_handler.cpp
savoirfairelinux_jami-daemon/src/jamidht/conversation_channel_handler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "jamidht/conversation_channel_handler.h" namespace jami { ConversationChannelHandler::ConversationChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm) : ChannelHandlerInterface() , account_(acc) , connectionManager_(cm) {} ConversationChannelHandler::~ConversationChannelHandler() {} void ConversationChannelHandler::connect(const DeviceId& deviceId, const std::string& channelName, ConnectCb&& cb) { connectionManager_.connectDevice(deviceId, "git://" + deviceId.toString() + "/" + channelName, std::move(cb)); } bool ConversationChannelHandler::onRequest(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& name) { auto acc = account_.lock(); if (!cert || !cert->issuer || !acc) return false; // Pre-check before acceptance. Sometimes, another device can start a conversation // which is still not synced. So, here we decline channel's request in this case // to avoid the other device to want to sync with us if we are not ready. auto sep = name.find_last_of('/'); auto conversationId = name.substr(sep + 1); if (auto acc = account_.lock()) if (auto convModule = acc->convModule(true)) { auto res = !convModule->isBanned(conversationId, cert->issuer->getId().toString()); res &= !convModule->isBanned(conversationId, cert->getLongId().toString()); return res; } return false; } void ConversationChannelHandler::onReady(const std::shared_ptr<dht::crypto::Certificate>&, const std::string&, std::shared_ptr<dhtnet::ChannelSocket>) {} } // namespace jami
2,667
C++
.cpp
60
36.033333
95
0.640385
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,797
channeled_transport.cpp
savoirfairelinux_jami-daemon/src/jamidht/channeled_transport.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "channeled_transport.h" #include "logger.h" #include <dhtnet/multiplexed_socket.h> #include "connectivity/sip_utils.h" #include <pjsip/sip_transport.h> #include <pjsip/sip_endpoint.h> #include <pj/compat/socket.h> #include <pj/lock.h> namespace jami { namespace tls { ChanneledSIPTransport::ChanneledSIPTransport(pjsip_endpoint* endpt, const std::shared_ptr<dhtnet::ChannelSocket>& socket, onShutdownCb&& cb) : socket_(socket) , shutdownCb_(std::move(cb)) , trData_() , pool_ {nullptr, pj_pool_release} , rxPool_(nullptr, pj_pool_release) { local_ = socket->getLocalAddress(); remote_ = socket->getRemoteAddress(); int tp_type = local_.isIpv6() ? PJSIP_TRANSPORT_TLS6 : PJSIP_TRANSPORT_TLS; JAMI_DBG("ChanneledSIPTransport@%p {tr=%p}", this, &trData_.base); // Init memory trData_.self = this; // up-link for PJSIP callbacks pool_ = sip_utils::smart_alloc_pool(endpt, "channeled.pool", sip_utils::POOL_TP_INIT, sip_utils::POOL_TP_INC); auto& base = trData_.base; std::memset(&base, 0, sizeof(base)); pj_ansi_snprintf(base.obj_name, PJ_MAX_OBJ_NAME, "chan%p", &base); base.endpt = endpt; base.tpmgr = pjsip_endpt_get_tpmgr(endpt); base.pool = pool_.get(); if (pj_atomic_create(pool_.get(), 0, &base.ref_cnt) != PJ_SUCCESS) throw std::runtime_error("Unable to create PJSIP atomic."); if (pj_lock_create_recursive_mutex(pool_.get(), "chan", &base.lock) != PJ_SUCCESS) throw std::runtime_error("Unable to create PJSIP mutex."); if (not local_) { JAMI_ERR("Invalid local address"); throw std::runtime_error("Invalid local address"); } if (not remote_) { JAMI_ERR("Invalid remote address"); throw std::runtime_error("Invalid remote address"); } pj_sockaddr_cp(&base.key.rem_addr, remote_.pjPtr()); base.key.type = tp_type; auto reg_type = static_cast<pjsip_transport_type_e>(tp_type); base.type_name = const_cast<char*>(pjsip_transport_get_type_name(reg_type)); base.flag = pjsip_transport_get_flag_from_type(reg_type); base.info = static_cast<char*>(pj_pool_alloc(pool_.get(), sip_utils::TRANSPORT_INFO_LENGTH)); auto remote_addr = remote_.toString(); pj_ansi_snprintf(base.info, sip_utils::TRANSPORT_INFO_LENGTH, "%s to %s", base.type_name, remote_addr.c_str()); base.addr_len = remote_.getLength(); base.dir = PJSIP_TP_DIR_NONE; // Set initial local address pj_sockaddr_cp(&base.local_addr, local_.pjPtr()); sip_utils::sockaddr_to_host_port(pool_.get(), &base.local_name, &base.local_addr); sip_utils::sockaddr_to_host_port(pool_.get(), &base.remote_name, remote_.pjPtr()); // Init transport callbacks base.send_msg = [](pjsip_transport* transport, pjsip_tx_data* tdata, const pj_sockaddr_t* rem_addr, int addr_len, void* token, pjsip_transport_callback callback) -> pj_status_t { auto* this_ = reinterpret_cast<ChanneledSIPTransport*>( reinterpret_cast<TransportData*>(transport)->self); return this_->send(tdata, rem_addr, addr_len, token, callback); }; base.do_shutdown = [](pjsip_transport* transport) -> pj_status_t { auto* this_ = reinterpret_cast<ChanneledSIPTransport*>( reinterpret_cast<TransportData*>(transport)->self); JAMI_DEBUG("ChanneledSIPTransport@{} tr={} rc={:d}: shutdown", fmt::ptr(this_), fmt::ptr(transport), pj_atomic_get(transport->ref_cnt)); if (this_->socket_) this_->socket_->shutdown(); return PJ_SUCCESS; }; base.destroy = [](pjsip_transport* transport) -> pj_status_t { auto* this_ = reinterpret_cast<ChanneledSIPTransport*>( reinterpret_cast<TransportData*>(transport)->self); JAMI_DEBUG("ChanneledSIPTransport@{}: destroying", fmt::ptr(this_)); delete this_; return PJ_SUCCESS; }; // Init rdata_ std::memset(&rdata_, 0, sizeof(pjsip_rx_data)); rxPool_ = sip_utils::smart_alloc_pool(endpt, "channeled.rxPool", PJSIP_POOL_RDATA_LEN, PJSIP_POOL_RDATA_LEN); rdata_.tp_info.pool = rxPool_.get(); rdata_.tp_info.transport = &base; rdata_.tp_info.tp_data = this; rdata_.tp_info.op_key.rdata = &rdata_; pj_ioqueue_op_key_init(&rdata_.tp_info.op_key.op_key, sizeof(pj_ioqueue_op_key_t)); rdata_.pkt_info.src_addr = base.key.rem_addr; rdata_.pkt_info.src_addr_len = sizeof(rdata_.pkt_info.src_addr); auto rem_addr = &base.key.rem_addr; pj_sockaddr_print(rem_addr, rdata_.pkt_info.src_name, sizeof(rdata_.pkt_info.src_name), 0); rdata_.pkt_info.src_port = pj_sockaddr_get_port(rem_addr); // Register callbacks if (pjsip_transport_register(base.tpmgr, &base) != PJ_SUCCESS) throw std::runtime_error("Unable to register PJSIP transport."); } void ChanneledSIPTransport::start() { // Link to Channel Socket socket_->setOnRecv([this](const uint8_t* buf, size_t len) { pj_gettimeofday(&rdata_.pkt_info.timestamp); size_t remaining {len}; while (remaining) { // Build rdata size_t added = std::min(remaining, (size_t) PJSIP_MAX_PKT_LEN - (size_t) rdata_.pkt_info.len); std::copy_n(buf, added, rdata_.pkt_info.packet + rdata_.pkt_info.len); rdata_.pkt_info.len += added; buf += added; remaining -= added; // Consume packet auto eaten = pjsip_tpmgr_receive_packet(trData_.base.tpmgr, &rdata_); if (eaten == rdata_.pkt_info.len) { rdata_.pkt_info.len = 0; } else if (eaten > 0) { memmove(rdata_.pkt_info.packet, rdata_.pkt_info.packet + eaten, eaten); rdata_.pkt_info.len -= eaten; } pj_pool_reset(rdata_.tp_info.pool); } return len; }); socket_->onShutdown([this] { disconnected_ = true; if (auto state_cb = pjsip_tpmgr_get_state_cb(trData_.base.tpmgr)) { JAMI_WARN("[SIPS] process disconnect event"); pjsip_transport_state_info state_info; std::memset(&state_info, 0, sizeof(state_info)); state_info.status = PJ_SUCCESS; (*state_cb)(&trData_.base, PJSIP_TP_STATE_DISCONNECTED, &state_info); } shutdownCb_(); }); } ChanneledSIPTransport::~ChanneledSIPTransport() { JAMI_DBG("~ChanneledSIPTransport@%p {tr=%p}", this, &trData_.base); auto base = getTransportBase(); // Here, we reset callbacks in ChannelSocket to avoid to call it after destruction // ChanneledSIPTransport is managed by pjsip, so we don't have any weak_ptr available socket_->setOnRecv([](const uint8_t*, size_t len) { return len; }); socket_->onShutdown([]() {}); // Stop low-level transport first socket_->shutdown(); socket_.reset(); // If delete not trigged by pjsip_transport_destroy (happen if objet not given to pjsip) if (not base->is_shutdown and not base->is_destroying) pjsip_transport_shutdown(base); pj_lock_destroy(base->lock); pj_atomic_destroy(base->ref_cnt); JAMI_DBG("~ChanneledSIPTransport@%p {tr=%p} bye", this, &trData_.base); } pj_status_t ChanneledSIPTransport::send(pjsip_tx_data* tdata, const pj_sockaddr_t* rem_addr, int addr_len, void*, pjsip_transport_callback) { // Sanity check PJ_ASSERT_RETURN(tdata, PJ_EINVAL); // Check that there's no pending operation associated with the tdata PJ_ASSERT_RETURN(tdata->op_key.tdata == nullptr, PJSIP_EPENDINGTX); // Check the address is supported PJ_ASSERT_RETURN(rem_addr and (addr_len == sizeof(pj_sockaddr_in) or addr_len == sizeof(pj_sockaddr_in6)), PJ_EINVAL); // Check in we are able to send it in synchronous way first std::size_t size = tdata->buf.cur - tdata->buf.start; if (socket_) { std::error_code ec; socket_->write(reinterpret_cast<const uint8_t*>(tdata->buf.start), size, ec); if (!ec) return PJ_SUCCESS; } return PJ_EINVAL; } } // namespace tls } // namespace jami
9,607
C++
.cpp
215
35.460465
98
0.603141
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,798
contact_list.cpp
savoirfairelinux_jami-daemon/src/jamidht/contact_list.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "contact_list.h" #include "logger.h" #include "jamiaccount.h" #include "fileutils.h" #include "manager.h" #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #endif #include "account_const.h" #include <fstream> #include <gnutls/ocsp.h> namespace jami { ContactList::ContactList(const std::string& accountId, const std::shared_ptr<crypto::Certificate>& cert, const std::filesystem::path& path, OnChangeCallback cb) : path_(path) , callbacks_(std::move(cb)) , accountId_(accountId) { if (cert) { trust_ = std::make_unique<dhtnet::tls::TrustStore>(jami::Manager::instance().certStore(accountId_)); accountTrust_.add(*cert); } } ContactList::~ContactList() {} void ContactList::load() { loadContacts(); loadTrustRequests(); loadKnownDevices(); } void ContactList::save() { saveContacts(); saveTrustRequests(); saveKnownDevices(); } bool ContactList::setCertificateStatus(const std::string& cert_id, const dhtnet::tls::TrustStore::PermissionStatus status) { if (contacts_.find(dht::InfoHash(cert_id)) != contacts_.end()) { JAMI_DBG("Unable to set certificate status for existing contacts %s", cert_id.c_str()); return false; } return trust_->setCertificateStatus(cert_id, status); } bool ContactList::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert, dhtnet::tls::TrustStore::PermissionStatus status, bool local) { return trust_->setCertificateStatus(cert, status, local); } bool ContactList::addContact(const dht::InfoHash& h, bool confirmed, const std::string& conversationId) { JAMI_WARN("[Contacts] addContact: %s, conversation: %s", h.to_c_str(), conversationId.c_str()); auto c = contacts_.find(h); if (c == contacts_.end()) c = contacts_.emplace(h, Contact {}).first; else if (c->second.isActive() and c->second.confirmed == confirmed && c->second.conversationId == conversationId) return false; c->second.added = std::time(nullptr); // NOTE: because we can re-add a contact after removing it // we should reset removed (as not removed anymore). This fix isActive() // if addContact is called just after removeContact during the same second c->second.removed = 0; c->second.conversationId = conversationId; c->second.confirmed |= confirmed; auto hStr = h.toString(); trust_->setCertificateStatus(hStr, dhtnet::tls::TrustStore::PermissionStatus::ALLOWED); saveContacts(); callbacks_.contactAdded(hStr, c->second.confirmed); return true; } void ContactList::updateConversation(const dht::InfoHash& h, const std::string& conversationId) { auto c = contacts_.find(h); if (c != contacts_.end() && c->second.conversationId != conversationId) { c->second.conversationId = conversationId; saveContacts(); } } bool ContactList::removeContact(const dht::InfoHash& h, bool ban) { std::unique_lock lk(mutex_); JAMI_WARN("[Contacts] removeContact: %s", h.to_c_str()); auto c = contacts_.find(h); if (c == contacts_.end()) c = contacts_.emplace(h, Contact {}).first; c->second.removed = std::time(nullptr); c->second.confirmed = false; c->second.banned = ban; auto uri = h.toString(); trust_->setCertificateStatus(uri, ban ? dhtnet::tls::TrustStore::PermissionStatus::BANNED : dhtnet::tls::TrustStore::PermissionStatus::UNDEFINED); if (trustRequests_.erase(h) > 0) saveTrustRequests(); saveContacts(); lk.unlock(); #ifdef ENABLE_PLUGIN auto filename = path_.filename().string(); jami::Manager::instance() .getJamiPluginManager() .getChatServicesManager() .cleanChatSubjects(filename, uri); #endif callbacks_.contactRemoved(uri, ban); return true; } bool ContactList::removeContactConversation(const dht::InfoHash& h) { auto c = contacts_.find(h); if (c == contacts_.end()) return false; c->second.conversationId = ""; saveContacts(); return true; } std::map<std::string, std::string> ContactList::getContactDetails(const dht::InfoHash& h) const { const auto c = contacts_.find(h); if (c == std::end(contacts_)) { JAMI_WARN("[Contacts] Contact '%s' not found", h.to_c_str()); return {}; } auto details = c->second.toMap(); if (not details.empty()) details["id"] = c->first.toString(); return details; } const std::map<dht::InfoHash, Contact>& ContactList::getContacts() const { return contacts_; } void ContactList::setContacts(const std::map<dht::InfoHash, Contact>& contacts) { contacts_ = contacts; saveContacts(); // Set contacts is used when creating a new device, so just announce new contacts for (auto& peer : contacts) if (peer.second.isActive()) callbacks_.contactAdded(peer.first.toString(), peer.second.confirmed); } void ContactList::updateContact(const dht::InfoHash& id, const Contact& contact, bool emit) { if (not id) { JAMI_ERR("[Contacts] updateContact: invalid contact ID"); return; } bool stateChanged {false}; auto c = contacts_.find(id); if (c == contacts_.end()) { // JAMI_DBG("[Contacts] New contact: %s", id.toString().c_str()); c = contacts_.emplace(id, contact).first; stateChanged = c->second.isActive() or c->second.isBanned(); } else { // JAMI_DBG("[Contacts] Updated contact: %s", id.toString().c_str()); stateChanged = c->second.update(contact); } if (stateChanged) { { std::lock_guard lk(mutex_); if (trustRequests_.erase(id) > 0) saveTrustRequests(); } if (c->second.isActive()) { trust_->setCertificateStatus(id.toString(), dhtnet::tls::TrustStore::PermissionStatus::ALLOWED); if (emit) callbacks_.contactAdded(id.toString(), c->second.confirmed); } else { if (c->second.banned) trust_->setCertificateStatus(id.toString(), dhtnet::tls::TrustStore::PermissionStatus::BANNED); if (emit) callbacks_.contactRemoved(id.toString(), c->second.banned); } } } void ContactList::loadContacts() { decltype(contacts_) contacts; try { // read file auto file = fileutils::loadFile("contacts", path_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); oh.get().convert(contacts); } catch (const std::exception& e) { JAMI_WARN("[Contacts] Error loading contacts: %s", e.what()); return; } for (auto& peer : contacts) updateContact(peer.first, peer.second, false); } void ContactList::saveContacts() const { std::ofstream file(path_ / "contacts", std::ios::trunc | std::ios::binary); msgpack::pack(file, contacts_); } void ContactList::saveTrustRequests() const { // mutex_ MUST BE locked std::ofstream file(path_ / "incomingTrustRequests", std::ios::trunc | std::ios::binary); msgpack::pack(file, trustRequests_); } void ContactList::loadTrustRequests() { if (!std::filesystem::is_regular_file(fileutils::getFullPath(path_, "incomingTrustRequests"))) return; std::map<dht::InfoHash, TrustRequest> requests; try { // read file auto file = fileutils::loadFile("incomingTrustRequests", path_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); oh.get().convert(requests); } catch (const std::exception& e) { JAMI_WARN("[Contacts] Error loading trust requests: %s", e.what()); return; } for (auto& tr : requests) onTrustRequest(tr.first, tr.second.device, tr.second.received, false, tr.second.conversationId, std::move(tr.second.payload)); } bool ContactList::onTrustRequest(const dht::InfoHash& peer_account, const std::shared_ptr<dht::crypto::PublicKey>& peer_device, time_t received, bool confirm, const std::string& conversationId, std::vector<uint8_t>&& payload) { bool accept = false; // Check existing contact std::unique_lock lk(mutex_); auto contact = contacts_.find(peer_account); bool active = false; if (contact != contacts_.end()) { // Banned contact: discard request if (contact->second.isBanned()) return false; if (contact->second.isActive()) { active = true; // Send confirmation if (not confirm) accept = true; if (not contact->second.confirmed) { contact->second.confirmed = true; callbacks_.contactAdded(peer_account.toString(), true); } } } if (not active) { auto req = trustRequests_.find(peer_account); if (req == trustRequests_.end()) { // Add trust request req = trustRequests_ .emplace(peer_account, TrustRequest {peer_device, conversationId, received, payload}) .first; } else { // Update trust request if (received > req->second.received) { req->second.device = peer_device; req->second.conversationId = conversationId; req->second.received = received; req->second.payload = payload; } else { JAMI_DBG("[Contacts] Ignoring outdated trust request from %s", peer_account.toString().c_str()); } } saveTrustRequests(); } lk.unlock(); // Note: call JamiAccount's callback to build ConversationRequest anyway if (!confirm) callbacks_.trustRequest(peer_account.toString(), conversationId, std::move(payload), received); else if (active) { // Only notify if confirmed + not removed callbacks_.onConfirmation(peer_account.toString(), conversationId); } return accept; } /* trust requests */ std::vector<std::map<std::string, std::string>> ContactList::getTrustRequests() const { using Map = std::map<std::string, std::string>; std::vector<Map> ret; std::lock_guard lk(mutex_); ret.reserve(trustRequests_.size()); for (const auto& r : trustRequests_) { ret.emplace_back( Map {{libjami::Account::TrustRequest::FROM, r.first.toString()}, {libjami::Account::TrustRequest::RECEIVED, std::to_string(r.second.received)}, {libjami::Account::TrustRequest::CONVERSATIONID, r.second.conversationId}, {libjami::Account::TrustRequest::PAYLOAD, std::string(r.second.payload.begin(), r.second.payload.end())}}); } return ret; } std::map<std::string, std::string> ContactList::getTrustRequest(const dht::InfoHash& from) const { using Map = std::map<std::string, std::string>; std::lock_guard lk(mutex_); auto r = trustRequests_.find(from); if (r == trustRequests_.end()) return {}; return Map {{libjami::Account::TrustRequest::FROM, r->first.toString()}, {libjami::Account::TrustRequest::RECEIVED, std::to_string(r->second.received)}, {libjami::Account::TrustRequest::CONVERSATIONID, r->second.conversationId}, {libjami::Account::TrustRequest::PAYLOAD, std::string(r->second.payload.begin(), r->second.payload.end())}}; } bool ContactList::acceptTrustRequest(const dht::InfoHash& from) { // The contact sent us a TR so we are in its contact list std::unique_lock lk(mutex_); auto i = trustRequests_.find(from); if (i == trustRequests_.end()) return false; auto convId = i->second.conversationId; // Clear trust request trustRequests_.erase(i); saveTrustRequests(); lk.unlock(); addContact(from, true, convId); return true; } void ContactList::acceptConversation(const std::string& convId, const std::string& deviceId) { if (callbacks_.acceptConversation) callbacks_.acceptConversation(convId, deviceId); } bool ContactList::discardTrustRequest(const dht::InfoHash& from) { std::lock_guard lk(mutex_); if (trustRequests_.erase(from) > 0) { saveTrustRequests(); return true; } return false; } void ContactList::loadKnownDevices() { try { // read file auto file = fileutils::loadFile("knownDevices", path_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::map<dht::PkId, std::pair<std::string, uint64_t>> knownDevices; oh.get().convert(knownDevices); for (const auto& d : knownDevices) { if (auto crt = jami::Manager::instance().certStore(accountId_).getCertificate(d.first.toString())) { if (not foundAccountDevice(crt, d.second.first, clock::from_time_t(d.second.second))) JAMI_WARN("[Contacts] Unable to add device %s", d.first.toString().c_str()); } else { JAMI_WARN("[Contacts] Unable to find certificate for device %s", d.first.toString().c_str()); } } } catch (const std::exception& e) { // Legacy fallback try { auto file = fileutils::loadFile("knownDevicesNames", path_); msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::map<dht::InfoHash, std::pair<std::string, uint64_t>> knownDevices; oh.get().convert(knownDevices); for (const auto& d : knownDevices) { if (auto crt = jami::Manager::instance().certStore(accountId_).getCertificate(d.first.toString())) { if (not foundAccountDevice(crt, d.second.first, clock::from_time_t(d.second.second))) JAMI_WARN("[Contacts] Unable to add device %s", d.first.toString().c_str()); } } } catch (const std::exception& e) { JAMI_WARN("[Contacts] Error loading devices: %s", e.what()); } return; } } void ContactList::saveKnownDevices() const { std::ofstream file(path_ / "knownDevices", std::ios::trunc | std::ios::binary); std::map<dht::PkId, std::pair<std::string, uint64_t>> devices; for (const auto& id : knownDevices_) devices.emplace(id.first, std::make_pair(id.second.name, clock::to_time_t(id.second.last_sync))); msgpack::pack(file, devices); } void ContactList::foundAccountDevice(const dht::PkId& device, const std::string& name, const time_point& updated) { // insert device auto it = knownDevices_.emplace(device, KnownDevice {{}, name, updated}); if (it.second) { JAMI_DBG("[Contacts] Found account device: %s %s", name.c_str(), device.toString().c_str()); saveKnownDevices(); callbacks_.devicesChanged(knownDevices_); } else { // update device name if (not name.empty() and it.first->second.name != name) { JAMI_DBG("[Contacts] Updating device name: %s %s", name.c_str(), device.toString().c_str()); it.first->second.name = name; saveKnownDevices(); callbacks_.devicesChanged(knownDevices_); } } } bool ContactList::foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, const std::string& name, const time_point& updated) { if (not crt) return false; auto id = crt->getLongId(); // match certificate chain auto verifyResult = accountTrust_.verify(*crt); if (not verifyResult) { JAMI_WARNING("[Contacts] Found invalid account device: {:s}: {:s}", id, verifyResult.toString()); return false; } // insert device auto it = knownDevices_.emplace(id, KnownDevice {crt, name, updated}); if (it.second) { JAMI_LOG("[Contacts] Found account device: {} {}", name, id); jami::Manager::instance().certStore(accountId_).pinCertificate(crt); if (crt->ocspResponse) { unsigned int status = crt->ocspResponse->getCertificateStatus(); if (status == GNUTLS_OCSP_CERT_REVOKED) { JAMI_ERROR("Certificate {} has revoked OCSP status", id); trust_->setCertificateStatus(crt, dhtnet::tls::TrustStore::PermissionStatus::BANNED, false); } } saveKnownDevices(); callbacks_.devicesChanged(knownDevices_); } else { // update device name if (not name.empty() and it.first->second.name != name) { JAMI_LOG("[Contacts] updating device name: {} {}", name, id); it.first->second.name = name; saveKnownDevices(); callbacks_.devicesChanged(knownDevices_); } } return true; } bool ContactList::removeAccountDevice(const dht::PkId& device) { if (knownDevices_.erase(device) > 0) { saveKnownDevices(); return true; } return false; } void ContactList::setAccountDeviceName(const dht::PkId& device, const std::string& name) { auto dev = knownDevices_.find(device); if (dev != knownDevices_.end()) { if (dev->second.name != name) { dev->second.name = name; saveKnownDevices(); callbacks_.devicesChanged(knownDevices_); } } } std::string ContactList::getAccountDeviceName(const dht::PkId& device) const { auto dev = knownDevices_.find(device); if (dev != knownDevices_.end()) { return dev->second.name; } return {}; } DeviceSync ContactList::getSyncData() const { DeviceSync sync_data; sync_data.date = clock::now().time_since_epoch().count(); // sync_data.device_name = deviceName_; sync_data.peers = getContacts(); static constexpr size_t MAX_TRUST_REQUESTS = 20; std::lock_guard lk(mutex_); if (trustRequests_.size() <= MAX_TRUST_REQUESTS) for (const auto& req : trustRequests_) sync_data.trust_requests.emplace(req.first, TrustRequest {req.second.device, req.second.conversationId, req.second.received, {}}); else { size_t inserted = 0; auto req = trustRequests_.lower_bound(dht::InfoHash::getRandom()); while (inserted++ < MAX_TRUST_REQUESTS) { if (req == trustRequests_.end()) req = trustRequests_.begin(); sync_data.trust_requests.emplace(req->first, TrustRequest {req->second.device, req->second.conversationId, req->second.received, {}}); ++req; } } for (const auto& dev : knownDevices_) { if (!dev.second.certificate) { JAMI_WARNING("No certificate found for {}", dev.first); continue; } sync_data.devices.emplace(dev.second.certificate->getLongId(), KnownDeviceSync {dev.second.name, dev.second.certificate->getId()}); } return sync_data; } bool ContactList::syncDevice(const dht::PkId& device, const time_point& syncDate) { auto it = knownDevices_.find(device); if (it == knownDevices_.end()) { JAMI_WARN("[Contacts] Dropping sync data from unknown device"); return false; } if (it->second.last_sync >= syncDate) { JAMI_DBG("[Contacts] Dropping outdated sync data"); return false; } it->second.last_sync = syncDate; return true; } } // namespace jami
21,682
C++
.cpp
589
28.271647
117
0.594744
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,799
typers.cpp
savoirfairelinux_jami-daemon/src/jamidht/typers.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "typers.h" #include "manager.h" #include "jamidht/jamiaccount.h" static constexpr std::chrono::steady_clock::duration COMPOSING_TIMEOUT {std::chrono::seconds(12)}; namespace jami { Typers::Typers(const std::shared_ptr<JamiAccount>& acc, const std::string& convId) : ioContext_(Manager::instance().ioContext()) , acc_(acc) , accountId_(acc->getAccountID()) , convId_(convId) , selfUri_(acc->getUsername()) { } Typers::~Typers() { for (auto& watcher : watcher_) { watcher.second.cancel(); } watcher_.clear(); } std::string getIsComposing(const std::string& conversationId, bool isWriting) { // implementing https://tools.ietf.org/rfc/rfc3994.txt return fmt::format("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" "<isComposing><state>{}</state>{}</isComposing>", isWriting ? "active"sv : "idle"sv, conversationId.empty() ? "" : "<conversation>" + conversationId + "</conversation>"); } void Typers::addTyper(const std::string &typer, bool sendMessage) { auto acc = acc_.lock(); if (!acc || !acc->isComposingEnabled()) return; auto [it, res] = watcher_.emplace(typer, asio::steady_timer {*ioContext_}); if (res) { auto& watcher = it->second; // Check next member watcher.expires_at(std::chrono::steady_clock::now() + COMPOSING_TIMEOUT); watcher.async_wait( std::bind(&Typers::onTyperTimeout, shared_from_this(), std::placeholders::_1, typer)); if (typer != selfUri_) emitSignal<libjami::ConfigurationSignal::ComposingStatusChanged>(accountId_, convId_, typer, 1); } if (sendMessage) { // In this case we should emit for remote to update the timer acc->sendInstantMessage(convId_, {{MIME_TYPE_IM_COMPOSING, getIsComposing(convId_, true)}}); } } void Typers::removeTyper(const std::string &typer, bool sendMessage) { auto acc = acc_.lock(); if (!acc || !acc->isComposingEnabled()) return; if (watcher_.erase(typer)) { if (sendMessage) { acc->sendInstantMessage(convId_, {{MIME_TYPE_IM_COMPOSING, getIsComposing(convId_, false)}}); } if (typer != selfUri_) { emitSignal<libjami::ConfigurationSignal::ComposingStatusChanged>(accountId_, convId_, typer, 0); } } } void Typers::onTyperTimeout(const asio::error_code& ec, const std::string &typer) { if (ec == asio::error::operation_aborted) return; removeTyper(typer); } } // namespace jami
3,968
C++
.cpp
102
27.852941
98
0.549818
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,800
message_channel_handler.cpp
savoirfairelinux_jami-daemon/src/jamidht/message_channel_handler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "jamidht/message_channel_handler.h" static constexpr const char MESSAGE_SCHEME[] {"msg:"}; namespace jami { using Key = std::pair<std::string, DeviceId>; struct MessageChannelHandler::Impl: public std::enable_shared_from_this<Impl> { std::weak_ptr<JamiAccount> account_; dhtnet::ConnectionManager& connectionManager_; std::recursive_mutex connectionsMtx_; std::map<Key, std::vector<std::shared_ptr<dhtnet::ChannelSocket>>> connections_; Impl(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm) : account_(acc) , connectionManager_(cm) {} void onChannelShutdown(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const std::string& peerId, const DeviceId& device); }; MessageChannelHandler::MessageChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm) : ChannelHandlerInterface() , pimpl_(std::make_shared<Impl>(acc, cm)) {} MessageChannelHandler::~MessageChannelHandler() {} void MessageChannelHandler::connect(const DeviceId& deviceId, const std::string&, ConnectCb&& cb) { auto channelName = MESSAGE_SCHEME + deviceId.toString(); if (pimpl_->connectionManager_.isConnecting(deviceId, channelName)) { JAMI_INFO("Already connecting to %s", deviceId.to_c_str()); return; } pimpl_->connectionManager_.connectDevice(deviceId, channelName, std::move(cb)); } void MessageChannelHandler::Impl::onChannelShutdown(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const std::string& peerId, const DeviceId& device) { std::lock_guard lk(connectionsMtx_); auto connectionsIt = connections_.find({peerId, device}); if (connectionsIt == connections_.end()) return; auto& connections = connectionsIt->second; auto conn = std::find(connections.begin(), connections.end(), socket); if (conn != connections.end()) connections.erase(conn); if (connections.empty()) connections_.erase(connectionsIt); } std::shared_ptr<dhtnet::ChannelSocket> MessageChannelHandler::getChannel(const std::string& peer, const DeviceId& deviceId) const { std::lock_guard lk(pimpl_->connectionsMtx_); auto it = pimpl_->connections_.find({peer, deviceId}); if (it == pimpl_->connections_.end()) return nullptr; if (it->second.empty()) return nullptr; return it->second.front(); } std::vector<std::shared_ptr<dhtnet::ChannelSocket>> MessageChannelHandler::getChannels(const std::string& peer) const { std::vector<std::shared_ptr<dhtnet::ChannelSocket>> sockets; std::lock_guard lk(pimpl_->connectionsMtx_); auto lower = pimpl_->connections_.lower_bound({peer, DeviceId()}); for (auto it = lower; it != pimpl_->connections_.end() && it->first.first == peer; ++it) sockets.insert(sockets.end(), it->second.begin(), it->second.end()); return sockets; } bool MessageChannelHandler::onRequest(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& /* name */) { auto acc = pimpl_->account_.lock(); if (!cert || !cert->issuer || !acc) return false; return true; //return cert->issuer->getId().toString() == acc->getUsername(); } void MessageChannelHandler::onReady(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string&, std::shared_ptr<dhtnet::ChannelSocket> socket) { auto acc = pimpl_->account_.lock(); if (!cert || !cert->issuer || !acc) return; auto peerId = cert->issuer->getId().toString(); auto device = cert->getLongId(); std::lock_guard lk(pimpl_->connectionsMtx_); pimpl_->connections_[{peerId, device}].emplace_back(socket); socket->onShutdown([w = pimpl_->weak_from_this(), peerId, device, s=std::weak_ptr(socket)]() { if (auto shared = w.lock()) shared->onChannelShutdown(s.lock(), peerId, device); }); struct DecodingContext { msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t, void*) { return true; }, nullptr, 1500}; }; socket->setOnRecv([acc = pimpl_->account_.lock(), peerId, ctx = std::make_shared<DecodingContext>() ](const uint8_t* buf, size_t len) { if (!buf || !acc) return len; ctx->pac.reserve_buffer(len); std::copy_n(buf, len, ctx->pac.buffer()); ctx->pac.buffer_consumed(len); msgpack::object_handle oh; try { while (ctx->pac.next(oh)) { Message msg; oh.get().convert(msg); acc->handleMessage(peerId, {msg.t, msg.c}); } } catch (const std::exception& e) { JAMI_WARNING("[convInfo] error on sync: {:s}", e.what()); } return len; }); } bool MessageChannelHandler::sendMessage(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const Message& message) { if (!socket) return false; msgpack::sbuffer buffer(UINT16_MAX); // Use max msgpack::pack(buffer, message); std::error_code ec; auto sent = socket->write(reinterpret_cast<const uint8_t*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_WARNING("Error sending message: {:s}", ec.message()); } return !ec && sent == buffer.size(); } } // namespace jami
6,266
C++
.cpp
153
34.379085
151
0.646199
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,801
account_manager.cpp
savoirfairelinux_jami-daemon/src/jamidht/account_manager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "account_manager.h" #include "accountarchive.h" #include "jamiaccount.h" #include "base64.h" #include "jami/account_const.h" #include "account_schema.h" #include "archiver.h" #include "manager.h" #include "libdevcrypto/Common.h" #include <opendht/thread_pool.h> #include <opendht/crypto.h> #include <exception> #include <future> #include <fstream> #include <gnutls/ocsp.h> namespace jami { AccountManager::CertRequest AccountManager::buildRequest(PrivateKey fDeviceKey) { return dht::ThreadPool::computation().get<std::unique_ptr<dht::crypto::CertificateRequest>>( [fDeviceKey = std::move(fDeviceKey)] { auto request = std::make_unique<dht::crypto::CertificateRequest>(); request->setName("Jami device"); const auto& deviceKey = fDeviceKey.get(); request->setUID(deviceKey->getPublicKey().getId().toString()); request->sign(*deviceKey); return request; }); } AccountManager::~AccountManager() { if (dht_) dht_->join(); } void AccountManager::onSyncData(DeviceSync&& sync, bool checkDevice) { auto sync_date = clock::time_point(clock::duration(sync.date)); if (checkDevice) { // If the DHT is used, we need to check the device here if (not info_->contacts->syncDevice(sync.owner->getLongId(), sync_date)) { return; } } // Sync known devices JAMI_DEBUG("[Contacts] received device sync data ({:d} devices, {:d} contacts)", sync.devices_known.size() + sync.devices.size(), sync.peers.size()); for (const auto& d : sync.devices_known) { findCertificate(d.first, [this, d](const std::shared_ptr<dht::crypto::Certificate>& crt) { if (not crt) return; // std::lock_guard lock(deviceListMutex_); foundAccountDevice(crt, d.second); }); } for (const auto& d : sync.devices) { findCertificate(d.second.sha1, [this, d](const std::shared_ptr<dht::crypto::Certificate>& crt) { if (not crt || crt->getLongId() != d.first) return; // std::lock_guard lock(deviceListMutex_); foundAccountDevice(crt, d.second.name); }); } // saveKnownDevices(); // Sync contacts for (const auto& peer : sync.peers) { info_->contacts->updateContact(peer.first, peer.second); } info_->contacts->saveContacts(); // Sync trust requests for (const auto& tr : sync.trust_requests) info_->contacts->onTrustRequest(tr.first, tr.second.device, tr.second.received, false, tr.second.conversationId, {}); } dht::crypto::Identity AccountManager::loadIdentity(const std::string& accountId, const std::string& crt_path, const std::string& key_path, const std::string& key_pwd) const { // Return to avoid unnecessary log if certificate or key is missing. Example case: when // importing an account when the certificate has not been unpacked from the archive. if (crt_path.empty() or key_path.empty()) return {}; JAMI_DEBUG("Loading certificate from '{}' and key from '{}' at {}", crt_path, key_path, path_); try { dht::crypto::Certificate dht_cert(fileutils::loadFile(crt_path, path_)); dht::crypto::PrivateKey dht_key(fileutils::loadFile(key_path, path_), key_pwd); auto crt_id = dht_cert.getLongId(); if (!crt_id or crt_id != dht_key.getPublicKey().getLongId()) { JAMI_ERR("Device certificate not matching public key!"); return {}; } auto& issuer = dht_cert.issuer; if (not issuer) { JAMI_ERROR("Device certificate {:s} has no issuer", dht_cert.getId().toString()); return {}; } // load revocation lists for device authority (account certificate). Manager::instance().certStore(accountId).loadRevocations(*issuer); return {std::make_shared<dht::crypto::PrivateKey>(std::move(dht_key)), std::make_shared<dht::crypto::Certificate>(std::move(dht_cert))}; } catch (const std::exception& e) { JAMI_ERR("Error loading identity: %s", e.what()); } return {}; } std::shared_ptr<dht::Value> AccountManager::parseAnnounce(const std::string& announceBase64, const std::string& accountId, const std::string& deviceSha1) { auto announce_val = std::make_shared<dht::Value>(); try { auto announce = base64::decode(announceBase64); msgpack::object_handle announce_msg = msgpack::unpack((const char*) announce.data(), announce.size()); announce_val->msgpack_unpack(announce_msg.get()); if (not announce_val->checkSignature()) { JAMI_ERR("[Auth] announce signature check failed"); return {}; } DeviceAnnouncement da; da.unpackValue(*announce_val); if (da.from.toString() != accountId or da.dev.toString() != deviceSha1) { JAMI_ERR("[Auth] device ID mismatch in announce"); return {}; } } catch (const std::exception& e) { JAMI_ERR("[Auth] unable to read announce: %s", e.what()); return {}; } return announce_val; } const AccountInfo* AccountManager::useIdentity(const std::string& accountId, const dht::crypto::Identity& identity, const std::string& receipt, const std::vector<uint8_t>& receiptSignature, const std::string& username, const OnChangeCallback& onChange) { accountId_ = accountId; if (receipt.empty() or receiptSignature.empty()) return nullptr; if (not identity.first or not identity.second) { JAMI_ERR("[Auth] no identity provided"); return nullptr; } auto accountCertificate = identity.second->issuer; if (not accountCertificate) { JAMI_ERR("[Auth] device certificate must be issued by the account certificate"); return nullptr; } // match certificate chain auto contactList = std::make_unique<ContactList>(accountId, accountCertificate, path_, onChange); auto result = contactList->isValidAccountDevice(*identity.second); if (not result) { JAMI_ERR("[Auth] unable to use identity: device certificate chain is unable to be verified: %s", result.toString().c_str()); return nullptr; } auto pk = accountCertificate->getSharedPublicKey(); JAMI_DBG("[Auth] checking device receipt for %s", pk->getId().toString().c_str()); if (!pk->checkSignature({receipt.begin(), receipt.end()}, receiptSignature)) { JAMI_ERR("[Auth] device receipt signature check failed"); return nullptr; } auto root = announceFromReceipt(receipt); if (!root.isMember("announce")) { JAMI_ERR() << this << " device receipt parsing error"; return nullptr; } auto dev_id = root["dev"].asString(); if (dev_id != identity.second->getId().toString()) { JAMI_ERR("[Auth] device ID mismatch between receipt and certificate"); return nullptr; } auto id = root["id"].asString(); if (id != pk->getId().toString()) { JAMI_ERR("[Auth] account ID mismatch between receipt and certificate"); return nullptr; } auto devicePk = identity.first->getSharedPublicKey(); if (!devicePk) { JAMI_ERR("[Auth] No device pk found"); return nullptr; } auto announce = parseAnnounce(root["announce"].asString(), id, devicePk->getId().toString()); if (not announce) { return nullptr; } onChange_ = std::move(onChange); auto info = std::make_unique<AccountInfo>(); info->identity = identity; info->contacts = std::move(contactList); info->contacts->load(); info->accountId = id; info->devicePk = std::move(devicePk); info->deviceId = info->devicePk->getLongId().toString(); info->announce = std::move(announce); info->ethAccount = root["eth"].asString(); info->username = username; info_ = std::move(info); JAMI_DBG("[Auth] Device %s receipt checked successfully for account %s", info_->deviceId.c_str(), id.c_str()); return info_.get(); } void AccountManager::reloadContacts() { if (info_) { info_->contacts->load(); } } Json::Value AccountManager::announceFromReceipt(const std::string& receipt) { Json::Value root; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(&receipt[0], &receipt[receipt.size()], &root, nullptr)) { JAMI_ERR() << this << " device receipt parsing error"; } return root; } void AccountManager::startSync(const OnNewDeviceCb& cb, const OnDeviceAnnouncedCb& dcb, bool publishPresence) { // Put device announcement if (info_->announce) { auto h = dht::InfoHash(info_->accountId); if (publishPresence) { dht_->put( h, info_->announce, [dcb = std::move(dcb), h](bool ok) { if (ok) JAMI_DEBUG("device announced at {}", h.toString()); // We do not care about the status, it's a permanent put, if this fail, // this means the DHT is disconnected but the put will be retried when connected. if (dcb) dcb(); }, {}, true); } for (const auto& crl : info_->identity.second->issuer->getRevocationLists()) dht_->put(h, crl, dht::DoneCallback {}, {}, true); dht_->listen<DeviceAnnouncement>(h, [this, cb = std::move(cb)](DeviceAnnouncement&& dev) { findCertificate(dev.dev, [this, cb](const std::shared_ptr<dht::crypto::Certificate>& crt) { foundAccountDevice(crt); if (cb) cb(crt); }); return true; }); dht_->listen<dht::crypto::RevocationList>(h, [this](dht::crypto::RevocationList&& crl) { if (crl.isSignedBy(*info_->identity.second->issuer)) { JAMI_DEBUG("found CRL for account."); certStore() .pinRevocationList(info_->accountId, std::make_shared<dht::crypto::RevocationList>( std::move(crl))); } return true; }); syncDevices(); } else { JAMI_WARNING("Unable to announce device: no announcement..."); } auto inboxKey = dht::InfoHash::get("inbox:" + info_->devicePk->getId().toString()); dht_->listen<dht::TrustRequest>(inboxKey, [this](dht::TrustRequest&& v) { if (v.service != DHT_TYPE_NS) return true; // allowPublic always true for trust requests (only forbidden if banned) onPeerMessage( *v.owner, true, [this, v](const std::shared_ptr<dht::crypto::Certificate>&, dht::InfoHash peer_account) mutable { JAMI_WARNING("Got trust request (confirm: {}) from: {} / {}. ConversationId: {}", v.confirm, peer_account.toString(), v.from.toString(), v.conversationId); if (info_) if (info_->contacts->onTrustRequest(peer_account, v.owner, time(nullptr), v.confirm, v.conversationId, std::move(v.payload))) { if (v.confirm) // No need to send a confirmation as already accepted here return; auto conversationId = v.conversationId; // Check if there was an old active conversation. auto details = info_->contacts->getContactDetails(peer_account); auto oldConvIt = details.find(libjami::Account::TrustRequest::CONVERSATIONID); if (oldConvIt != details.end() && oldConvIt->second != "") { if (conversationId == oldConvIt->second) { // Here, it's possible that we already have accepted the conversation // but contact were offline and sync failed. // So, retrigger the callback so upper layer will clone conversation if needed // instead of getting stuck in sync. info_->contacts->acceptConversation(conversationId, v.owner->getLongId().toString()); return; } conversationId = oldConvIt->second; JAMI_WARNING("Accept with old convId: {}", conversationId); } sendTrustRequestConfirm(peer_account, conversationId); } }); return true; }); } const std::map<dht::PkId, KnownDevice>& AccountManager::getKnownDevices() const { return info_->contacts->getKnownDevices(); } bool AccountManager::foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, const std::string& name, const time_point& last_sync) { return info_->contacts->foundAccountDevice(crt, name, last_sync); } void AccountManager::setAccountDeviceName(const std::string& name) { if (info_) info_->contacts->setAccountDeviceName(DeviceId(info_->deviceId), name); } std::string AccountManager::getAccountDeviceName() const { if (info_) return info_->contacts->getAccountDeviceName(DeviceId(info_->deviceId)); return {}; } bool AccountManager::foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, dht::InfoHash& account_id) { if (not crt) return false; auto top_issuer = crt; while (top_issuer->issuer) top_issuer = top_issuer->issuer; // Device certificate is unable to be self-signed if (top_issuer == crt) { JAMI_WARN("Found invalid peer device: %s", crt->getLongId().toString().c_str()); return false; } // Check peer certificate chain // Trust store with top issuer as the only CA dht::crypto::TrustList peer_trust; peer_trust.add(*top_issuer); if (not peer_trust.verify(*crt)) { JAMI_WARN("Found invalid peer device: %s", crt->getLongId().toString().c_str()); return false; } // Check cached OCSP response if (crt->ocspResponse and crt->ocspResponse->getCertificateStatus() != GNUTLS_OCSP_CERT_GOOD) { JAMI_ERR("Certificate %s is disabled by cached OCSP response", crt->getLongId().to_c_str()); return false; } account_id = crt->issuer->getId(); JAMI_WARN("Found peer device: %s account:%s CA:%s", crt->getLongId().toString().c_str(), account_id.toString().c_str(), top_issuer->getId().toString().c_str()); return true; } void AccountManager::onPeerMessage(const dht::crypto::PublicKey& peer_device, bool allowPublic, std::function<void(const std::shared_ptr<dht::crypto::Certificate>& crt, const dht::InfoHash& peer_account)>&& cb) { // quick check in case we already explicilty banned this device auto trustStatus = getCertificateStatus(peer_device.toString()); if (trustStatus == dhtnet::tls::TrustStore::PermissionStatus::BANNED) { JAMI_WARN("[Auth] Discarding message from banned device %s", peer_device.toString().c_str()); return; } findCertificate(peer_device.getId(), [this, cb = std::move(cb), allowPublic]( const std::shared_ptr<dht::crypto::Certificate>& cert) { dht::InfoHash peer_account_id; if (onPeerCertificate(cert, allowPublic, peer_account_id)) { cb(cert, peer_account_id); } }); } bool AccountManager::onPeerCertificate(const std::shared_ptr<dht::crypto::Certificate>& cert, bool allowPublic, dht::InfoHash& account_id) { dht::InfoHash peer_account_id; if (not foundPeerDevice(cert, peer_account_id)) { JAMI_WARN("[Auth] Discarding message from invalid peer certificate"); return false; } if (not isAllowed(*cert, allowPublic)) { JAMI_WARN("[Auth] Discarding message from unauthorized peer %s.", peer_account_id.toString().c_str()); return false; } account_id = peer_account_id; return true; } bool AccountManager::addContact(const dht::InfoHash& uri, bool confirmed, const std::string& conversationId) { JAMI_WARNING("AccountManager::addContact {}", confirmed); if (not info_) { JAMI_ERROR("addContact(): account not loaded"); return false; } if (info_->contacts->addContact(uri, confirmed, conversationId)) { syncDevices(); return true; } return false; } void AccountManager::removeContact(const std::string& uri, bool banned) { dht::InfoHash h(uri); if (not h) { JAMI_ERROR("removeContact: invalid contact URI"); return; } if (not info_) { JAMI_ERROR("addContact(): account not loaded"); return; } if (info_->contacts->removeContact(h, banned)) syncDevices(); } void AccountManager::removeContactConversation(const std::string& uri) { dht::InfoHash h(uri); if (not h) { JAMI_ERR("removeContact: invalid contact URI"); return; } if (not info_) { JAMI_ERR("addContact(): account not loaded"); return; } if (info_->contacts->removeContactConversation(h)) syncDevices(); } void AccountManager::updateContactConversation(const std::string& uri, const std::string& convId) { dht::InfoHash h(uri); if (not h) { JAMI_ERR("removeContact: invalid contact URI"); return; } if (not info_) { JAMI_ERR("addContact(): account not loaded"); return; } info_->contacts->updateConversation(h, convId); // Also decline trust request if there is one auto req = info_->contacts->getTrustRequest(h); if (req.find(libjami::Account::TrustRequest::CONVERSATIONID) != req.end() && req.at(libjami::Account::TrustRequest::CONVERSATIONID) == convId) { discardTrustRequest(uri); } syncDevices(); } std::vector<std::map<std::string, std::string>> AccountManager::getContacts(bool includeRemoved) const { if (not info_) { JAMI_ERR("getContacts(): account not loaded"); return {}; } const auto& contacts = info_->contacts->getContacts(); std::vector<std::map<std::string, std::string>> ret; ret.reserve(contacts.size()); for (const auto& c : contacts) { if (!c.second.isActive() && !includeRemoved && !c.second.isBanned()) continue; auto details = c.second.toMap(); if (not details.empty()) { details["id"] = c.first.toString(); ret.emplace_back(std::move(details)); } } return ret; } /** Obtain details about one account contact in serializable form. */ std::map<std::string, std::string> AccountManager::getContactDetails(const std::string& uri) const { if (!info_) { JAMI_ERR("getContactDetails(): account not loaded"); return {}; } dht::InfoHash h(uri); if (not h) { JAMI_ERR("getContactDetails: invalid contact URI"); return {}; } return info_->contacts->getContactDetails(h); } bool AccountManager::findCertificate( const dht::InfoHash& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb) { if (auto cert = certStore().getCertificate(h.toString())) { if (cb) cb(cert); } else if (dht_) { dht_->findCertificate(h, [cb = std::move(cb), this]( const std::shared_ptr<dht::crypto::Certificate>& crt) { if (crt && info_) { certStore().pinCertificate(crt); } if (cb) cb(crt); }); } return true; } bool AccountManager::findCertificate( const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb) { if (auto cert = certStore().getCertificate(id.toString())) { if (cb) cb(cert); } else if (auto cert = certStore().getCertificateLegacy(fileutils::get_data_dir().string(), id.toString())) { if (cb) cb(cert); } else if (cb) cb(nullptr); return true; } bool AccountManager::setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status) { return info_ and info_->contacts->setCertificateStatus(cert_id, status); } bool AccountManager::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert, dhtnet::tls::TrustStore::PermissionStatus status, bool local) { return info_ and info_->contacts->setCertificateStatus(cert, status, local); } std::vector<std::string> AccountManager::getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status) { return info_ ? info_->contacts->getCertificatesByStatus(status) : std::vector<std::string> {}; } dhtnet::tls::TrustStore::PermissionStatus AccountManager::getCertificateStatus(const std::string& cert_id) const { return info_ ? info_->contacts->getCertificateStatus(cert_id) : dhtnet::tls::TrustStore::PermissionStatus::UNDEFINED; } bool AccountManager::isAllowed(const crypto::Certificate& crt, bool allowPublic) { return info_ and info_->contacts->isAllowed(crt, allowPublic); } std::vector<std::map<std::string, std::string>> AccountManager::getTrustRequests() const { if (not info_) { JAMI_ERR("getTrustRequests(): account not loaded"); return {}; } return info_->contacts->getTrustRequests(); } bool AccountManager::acceptTrustRequest(const std::string& from, bool includeConversation) { dht::InfoHash f(from); if (info_) { auto req = info_->contacts->getTrustRequest(dht::InfoHash(from)); if (info_->contacts->acceptTrustRequest(f)) { sendTrustRequestConfirm(f, includeConversation ? req[libjami::Account::TrustRequest::CONVERSATIONID] : ""); syncDevices(); return true; } return false; } return false; } bool AccountManager::discardTrustRequest(const std::string& from) { dht::InfoHash f(from); return info_ and info_->contacts->discardTrustRequest(f); } void AccountManager::sendTrustRequest(const std::string& to, const std::string& convId, const std::vector<uint8_t>& payload) { JAMI_WARN("AccountManager::sendTrustRequest"); auto toH = dht::InfoHash(to); if (not toH) { JAMI_ERR("Unable to send trust request to invalid hash: %s", to.c_str()); return; } if (not info_) { JAMI_ERR("sendTrustRequest(): account not loaded"); return; } if (info_->contacts->addContact(toH, false, convId)) { syncDevices(); } forEachDevice(toH, [this, toH, convId, payload](const std::shared_ptr<dht::crypto::PublicKey>& dev) { auto to = toH.toString(); JAMI_WARNING("sending trust request to: {:s} / {:s}", to, dev->getLongId().toString()); dht_->putEncrypted(dht::InfoHash::get("inbox:" + dev->getId().toString()), dev, dht::TrustRequest(DHT_TYPE_NS, convId, payload), [to, size = payload.size()](bool ok) { if (!ok) JAMI_ERROR("Tried to send request {:s} (size: " "{:d}), but put failed", to, size); }); }); } void AccountManager::sendTrustRequestConfirm(const dht::InfoHash& toH, const std::string& convId) { JAMI_WARN("AccountManager::sendTrustRequestConfirm"); dht::TrustRequest answer {DHT_TYPE_NS, ""}; answer.confirm = true; answer.conversationId = convId; if (!convId.empty() && info_) info_->contacts->acceptConversation(convId); forEachDevice(toH, [this, toH, answer](const std::shared_ptr<dht::crypto::PublicKey>& dev) { JAMI_WARN("sending trust request reply: %s / %s", toH.toString().c_str(), dev->getLongId().toString().c_str()); dht_->putEncrypted(dht::InfoHash::get("inbox:" + dev->getId().toString()), dev, answer); }); } void AccountManager::forEachDevice( const dht::InfoHash& to, std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op, std::function<void(bool)>&& end) { if (not dht_) { JAMI_ERR("forEachDevice: no dht"); if (end) end(false); return; } dht_->get<dht::crypto::RevocationList>(to, [to, this](dht::crypto::RevocationList&& crl) { certStore().pinRevocationList(to.toString(), std::move(crl)); return true; }); struct State { // Note: state is initialized to 1, because we need to wait that the get is finished unsigned remaining {1}; std::set<dht::PkId> treatedDevices {}; std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)> onDevice; std::function<void(bool)> onEnd; void found(std::shared_ptr<dht::crypto::PublicKey> pk) { remaining--; if (pk && *pk) { auto longId = pk->getLongId(); if (treatedDevices.emplace(longId).second) { onDevice(pk); } } ended(); } void ended() { if (remaining == 0 && onEnd) { JAMI_DEBUG("Found {:d} devices", treatedDevices.size()); onEnd(not treatedDevices.empty()); onDevice = {}; onEnd = {}; } } }; auto state = std::make_shared<State>(); state->onDevice = std::move(op); state->onEnd = std::move(end); dht_->get<DeviceAnnouncement>( to, [this, to, state](DeviceAnnouncement&& dev) { if (dev.from != to) return true; state->remaining++; findCertificate(dev.dev, [state](const std::shared_ptr<dht::crypto::Certificate>& cert) { state->found(cert ? cert->getSharedPublicKey() : std::shared_ptr<dht::crypto::PublicKey> {}); }); return true; }, [state](bool /*ok*/) { state->found({}); }); } void AccountManager::lookupUri(const std::string& name, const std::string& defaultServer, LookupCallback cb) { nameDir_.get().lookupUri(name, defaultServer, std::move(cb)); } void AccountManager::lookupAddress(const std::string& addr, LookupCallback cb) { nameDir_.get().lookupAddress(addr, cb); } dhtnet::tls::CertificateStore& AccountManager::certStore() const { return Manager::instance().certStore(info_->contacts->accountId()); } } // namespace jami
30,190
C++
.cpp
771
28.767834
117
0.565518
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,802
gitserver.cpp
savoirfairelinux_jami-daemon/src/jamidht/gitserver.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "gitserver.h" #include "fileutils.h" #include "logger.h" #include "gittransport.h" #include "manager.h" #include <opendht/thread_pool.h> #include <dhtnet/multiplexed_socket.h> #include <fmt/compile.h> #include <charconv> #include <ctime> #include <fstream> #include <git2.h> #include <iomanip> using namespace std::string_view_literals; constexpr auto FLUSH_PKT = "0000"sv; constexpr auto NAK_PKT = "0008NAK\n"sv; constexpr auto DONE_CMD = "done\n"sv; constexpr auto WANT_CMD = "want"sv; constexpr auto HAVE_CMD = "have"sv; constexpr auto SERVER_CAPABILITIES = " HEAD\0side-band side-band-64k shallow no-progress include-tag"sv; namespace jami { class GitServer::Impl { public: Impl(const std::string& repositoryId, const std::string& repository, const std::shared_ptr<dhtnet::ChannelSocket>& socket) : repositoryId_(repositoryId) , repository_(repository) , socket_(socket) { // Check at least if repository is correct git_repository* repo; if (git_repository_open(&repo, repository_.c_str()) != 0) { socket_->shutdown(); return; } git_repository_free(repo); socket_->setOnRecv([this](const uint8_t* buf, std::size_t len) { std::lock_guard lk(destroyMtx_); if (isDestroying_) return len; if (parseOrder(std::string_view((const char*)buf, len))) while(parseOrder()); return len; }); } ~Impl() { stop(); } void stop() { std::lock_guard lk(destroyMtx_); if (isDestroying_.exchange(true)) { socket_->setOnRecv({}); socket_->shutdown(); } } bool parseOrder(std::string_view buf = {}); void sendReferenceCapabilities(bool sendVersion = false); bool NAK(); void ACKCommon(); bool ACKFirst(); void sendPackData(); std::map<std::string, std::string> getParameters(std::string_view pkt_line); std::string repositoryId_ {}; std::string repository_ {}; std::shared_ptr<dhtnet::ChannelSocket> socket_ {}; std::string wantedReference_ {}; std::string common_ {}; std::vector<std::string> haveRefs_ {}; std::string cachedPkt_ {}; std::mutex destroyMtx_ {}; std::atomic_bool isDestroying_ {false}; onFetchedCb onFetchedCb_ {}; }; bool GitServer::Impl::parseOrder(std::string_view buf) { std::string pkt = std::move(cachedPkt_); if (!buf.empty()) pkt += buf; // Parse pkt len // Reference: https://github.com/git/git/blob/master/Documentation/technical/protocol-common.txt#L51 // The first four bytes define the length of the packet and 0000 is a FLUSH pkt unsigned int pkt_len = 0; auto [p, ec] = std::from_chars(pkt.data(), pkt.data() + 4, pkt_len, 16); if (ec != std::errc()) { JAMI_ERROR("Unable to parse packet size"); } if (pkt_len != pkt.size()) { // Store next packet part if (pkt_len == 0) { // FLUSH_PKT pkt_len = 4; } cachedPkt_ = pkt.substr(pkt_len); } auto pack = std::string_view(pkt).substr(4, pkt_len - 4); if (pack == DONE_CMD) { // Reference: // https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L390 Do // not do multi-ack, just send ACK + pack file // In case of no common base, send NAK JAMI_INFO("Peer negotiation is done. Answering to want order"); bool sendData; if (common_.empty()) sendData = NAK(); else sendData = ACKFirst(); if (sendData) sendPackData(); return !cachedPkt_.empty(); } else if (pack.empty()) { if (!haveRefs_.empty()) { // Reference: // https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L390 // Do not do multi-ack, just send ACK + pack file In case of no common base ACK ACKCommon(); NAK(); } return !cachedPkt_.empty(); } auto lim = pack.find(' '); auto cmd = pack.substr(0, lim); auto dat = (lim < pack.size()) ? pack.substr(lim+1) : std::string_view{}; if (cmd == UPLOAD_PACK_CMD) { // Cf: https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L166 // References discovery JAMI_INFO("Upload pack command detected."); auto version = 1; auto parameters = getParameters(dat); auto versionIt = parameters.find("version"); bool sendVersion = false; if (versionIt != parameters.end()) { try { version = std::stoi(versionIt->second); sendVersion = true; } catch (...) { JAMI_WARNING("Invalid version detected: {}", versionIt->second); } } if (version == 1) { sendReferenceCapabilities(sendVersion); } else { JAMI_ERR("That protocol version is not yet supported (version: %u)", version); } } else if (cmd == WANT_CMD) { // Reference: // https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L229 // TODO can have more want wantedReference_ = dat.substr(0, 40); JAMI_INFO("Peer want ref: %s", wantedReference_.c_str()); } else if (cmd == HAVE_CMD) { const auto& commit = haveRefs_.emplace_back(dat.substr(0, 40)); if (common_.empty()) { // Detect first common commit // Reference: // https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L390 // TODO do not open repository every time git_repository* repo; if (git_repository_open(&repo, repository_.c_str()) != 0) { JAMI_WARN("Unable to open %s", repository_.c_str()); return !cachedPkt_.empty(); } GitRepository rep {repo, git_repository_free}; git_oid commit_id; if (git_oid_fromstr(&commit_id, commit.c_str()) == 0) { // Reference found common_ = commit; } } } else { JAMI_WARNING("Unwanted packet received: {}", pkt); } return !cachedPkt_.empty(); } std::string toGitHex(size_t value) { return fmt::format(FMT_COMPILE("{:04x}"), value & 0x0FFFF); } void GitServer::Impl::sendReferenceCapabilities(bool sendVersion) { // Get references // First, get the HEAD reference // https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L166 git_repository* repo; if (git_repository_open(&repo, repository_.c_str()) != 0) { JAMI_WARNING("Unable to open {}", repository_); socket_->shutdown(); return; } GitRepository rep {repo, git_repository_free}; // Answer with the version number // **** When the client initially connects the server will immediately respond // **** with a version number (if "version=1" is sent as an Extra Parameter), std::error_code ec; if (sendVersion) { auto toSend = "000eversion 1\0"sv; socket_->write(reinterpret_cast<const unsigned char*>(toSend.data()), toSend.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); socket_->shutdown(); return; } } git_oid commit_id; if (git_reference_name_to_id(&commit_id, rep.get(), "HEAD") < 0) { JAMI_ERROR("Unable to get reference for HEAD"); socket_->shutdown(); return; } std::string currentHead = git_oid_tostr_s(&commit_id); // Send references std::ostringstream packet; packet << toGitHex(5 + currentHead.size() + SERVER_CAPABILITIES.size()); packet << currentHead << SERVER_CAPABILITIES << "\n"; // Now, add other references git_strarray refs; if (git_reference_list(&refs, rep.get()) == 0) { for (std::size_t i = 0; i < refs.count; ++i) { std::string_view ref = refs.strings[i]; if (git_reference_name_to_id(&commit_id, rep.get(), ref.data()) < 0) { JAMI_WARNING("Unable to get reference for {}", ref); continue; } currentHead = git_oid_tostr_s(&commit_id); packet << toGitHex(6 /* size + space + \n */ + currentHead.size() + ref.size()); packet << currentHead << " " << ref << "\n"; } } git_strarray_dispose(&refs); // And add FLUSH packet << FLUSH_PKT; auto toSend = packet.str(); socket_->write(reinterpret_cast<const unsigned char*>(toSend.data()), toSend.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); socket_->shutdown(); } } void GitServer::Impl::ACKCommon() { std::error_code ec; // Ack common base if (!common_.empty()) { auto toSend = fmt::format(FMT_COMPILE("{:04x}ACK {} continue\n"), 18 + common_.size() /* size + ACK + space * 2 + continue + \n */, common_); socket_->write(reinterpret_cast<const unsigned char*>(toSend.c_str()), toSend.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); socket_->shutdown(); } } } bool GitServer::Impl::ACKFirst() { std::error_code ec; // Ack common base if (!common_.empty()) { auto toSend = fmt::format(FMT_COMPILE("{:04x}ACK {}\n"), 9 + common_.size() /* size + ACK + space + \n */, common_); socket_->write(reinterpret_cast<const unsigned char*>(toSend.c_str()), toSend.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); socket_->shutdown(); return false; } } return true; } bool GitServer::Impl::NAK() { std::error_code ec; // NAK socket_->write(reinterpret_cast<const unsigned char*>(NAK_PKT.data()), NAK_PKT.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); socket_->shutdown(); return false; } return true; } void GitServer::Impl::sendPackData() { git_repository* repo_ptr; if (git_repository_open(&repo_ptr, repository_.c_str()) != 0) { JAMI_WARN("Unable to open %s", repository_.c_str()); return; } GitRepository repo {repo_ptr, git_repository_free}; git_packbuilder* pb_ptr; if (git_packbuilder_new(&pb_ptr, repo.get()) != 0) { JAMI_WARNING("Unable to open packbuilder for {}", repository_); return; } GitPackBuilder pb {pb_ptr, git_packbuilder_free}; std::string fetched = wantedReference_; git_oid oid; if (git_oid_fromstr(&oid, fetched.c_str()) < 0) { JAMI_ERROR("Unable to get reference for commit {}", fetched); return; } git_revwalk* walker_ptr = nullptr; if (git_revwalk_new(&walker_ptr, repo.get()) < 0 || git_revwalk_push(walker_ptr, &oid) < 0) { if (walker_ptr) git_revwalk_free(walker_ptr); return; } GitRevWalker walker {walker_ptr, git_revwalk_free}; git_revwalk_sorting(walker.get(), GIT_SORT_TOPOLOGICAL); // Add first commit std::set<std::string> parents; auto haveCommit = false; while (!git_revwalk_next(&oid, walker.get())) { // log until have refs std::string id = git_oid_tostr_s(&oid); haveCommit |= std::find(haveRefs_.begin(), haveRefs_.end(), id) != haveRefs_.end(); auto itParents = std::find(parents.begin(), parents.end(), id); if (itParents != parents.end()) parents.erase(itParents); if (haveCommit && parents.size() == 0 /* We are sure that all commits are there */) break; if (git_packbuilder_insert_commit(pb.get(), &oid) != 0) { JAMI_WARN("Unable to open insert commit %s for %s", git_oid_tostr_s(&oid), repository_.c_str()); return; } // Get next commit to pack git_commit* commit_ptr; if (git_commit_lookup(&commit_ptr, repo.get(), &oid) < 0) { JAMI_ERR("Unable to look up current commit"); return; } GitCommit commit {commit_ptr, git_commit_free}; auto parentsCount = git_commit_parentcount(commit.get()); for (unsigned int p = 0; p < parentsCount; ++p) { // make sure to explore all branches const git_oid* pid = git_commit_parent_id(commit.get(), p); if (pid) parents.emplace(git_oid_tostr_s(pid)); } } git_buf data = {}; if (git_packbuilder_write_buf(&data, pb.get()) != 0) { JAMI_WARN("Unable to write pack data for %s", repository_.c_str()); return; } std::size_t sent = 0; std::size_t len = data.size; std::error_code ec; std::vector<uint8_t> toSendData; do { // cf https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt#L166 // In 'side-band-64k' mode it will send up to 65519 data bytes plus 1 control code, for a // total of up to 65520 bytes in a pkt-line. std::size_t pkt_size = std::min(static_cast<std::size_t>(65515), len - sent); std::string toSendHeader = toGitHex(pkt_size + 5); toSendData.clear(); toSendData.reserve(pkt_size + 5); toSendData.insert(toSendData.end(), toSendHeader.begin(), toSendHeader.end()); toSendData.push_back(0x1); toSendData.insert(toSendData.end(), data.ptr + sent, data.ptr + sent + pkt_size); socket_->write(reinterpret_cast<const unsigned char*>(toSendData.data()), toSendData.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); git_buf_dispose(&data); return; } sent += pkt_size; } while (sent < len); git_buf_dispose(&data); toSendData = {}; // And finish by a little FLUSH socket_->write(reinterpret_cast<const uint8_t*>(FLUSH_PKT.data()), FLUSH_PKT.size(), ec); if (ec) { JAMI_WARNING("Unable to send data for {}: {}", repository_, ec.message()); } // Clear sent data haveRefs_.clear(); wantedReference_.clear(); common_.clear(); if (onFetchedCb_) onFetchedCb_(fetched); } std::map<std::string, std::string> GitServer::Impl::getParameters(std::string_view pkt_line) { std::map<std::string, std::string> parameters; std::string key, value; auto isKey = true; auto nullChar = 0; for (auto letter: pkt_line) { if (letter == '\0') { // parameters such as host or version are after the first \0 if (nullChar != 0 && !key.empty()) { parameters[std::move(key)] = std::move(value); } nullChar += 1; isKey = true; key.clear(); value.clear(); } else if (letter == '=') { isKey = false; } else if (nullChar != 0) { if (isKey) { key += letter; } else { value += letter; } } } return parameters; } GitServer::GitServer(const std::string& accountId, const std::string& conversationId, const std::shared_ptr<dhtnet::ChannelSocket>& client) { auto path = (fileutils::get_data_dir() / accountId / "conversations" / conversationId).string(); pimpl_ = std::make_unique<GitServer::Impl>(conversationId, path, client); } GitServer::~GitServer() { stop(); pimpl_.reset(); JAMI_INFO("GitServer destroyed"); } void GitServer::setOnFetched(const onFetchedCb& cb) { if (!pimpl_) return; pimpl_->onFetchedCb_ = cb; } void GitServer::stop() { pimpl_->stop(); } } // namespace jami
16,928
C++
.cpp
465
28.963441
104
0.587895
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,803
server_account_manager.cpp
savoirfairelinux_jami-daemon/src/jamidht/server_account_manager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "server_account_manager.h" #include "base64.h" #include "jami/account_const.h" #include "fileutils.h" #include <opendht/http.h> #include <opendht/log.h> #include <opendht/thread_pool.h> #include "conversation_module.h" #include "jamiaccount.h" #include "manager.h" #include <algorithm> #include <string_view> using namespace std::literals; namespace jami { using Request = dht::http::Request; #define JAMI_PATH_LOGIN "/api/login" #define JAMI_PATH_AUTH "/api/auth" constexpr std::string_view PATH_DEVICE = JAMI_PATH_AUTH "/device"; constexpr std::string_view PATH_DEVICES = JAMI_PATH_AUTH "/devices"; constexpr std::string_view PATH_SEARCH = JAMI_PATH_AUTH "/directory/search"; constexpr std::string_view PATH_CONTACTS = JAMI_PATH_AUTH "/contacts"; constexpr std::string_view PATH_CONVERSATIONS = JAMI_PATH_AUTH "/conversations"; constexpr std::string_view PATH_CONVERSATIONS_REQUESTS = JAMI_PATH_AUTH "/conversationRequests"; constexpr std::string_view PATH_BLUEPRINT = JAMI_PATH_AUTH "/policyData"; ServerAccountManager::ServerAccountManager(const std::filesystem::path& path, const std::string& managerHostname, const std::string& nameServer) : AccountManager(path, nameServer) , managerHostname_(managerHostname) , logger_(Logger::dhtLogger()) {} void ServerAccountManager::setAuthHeaderFields(Request& request) const { request.set_header_field(restinio::http_field_t::authorization, "Bearer " + token_); } void ServerAccountManager::initAuthentication(const std::string& accountId, PrivateKey key, std::string deviceName, std::unique_ptr<AccountCredentials> credentials, AuthSuccessCallback onSuccess, AuthFailureCallback onFailure, const OnChangeCallback& onChange) { auto ctx = std::make_shared<AuthContext>(); ctx->accountId = accountId; ctx->key = key; ctx->request = buildRequest(key); ctx->deviceName = std::move(deviceName); ctx->credentials = dynamic_unique_cast<ServerAccountCredentials>(std::move(credentials)); ctx->onSuccess = std::move(onSuccess); ctx->onFailure = std::move(onFailure); if (not ctx->credentials or ctx->credentials->username.empty()) { ctx->onFailure(AuthError::INVALID_ARGUMENTS, "invalid credentials"); return; } onChange_ = std::move(onChange); const std::string url = managerHostname_ + PATH_DEVICE; JAMI_WARN("[Auth] Authentication with: %s to %s", ctx->credentials->username.c_str(), url.c_str()); dht::ThreadPool::computation().run([ctx, url, w=weak_from_this()] { auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (not this_) return; Json::Value body; { auto csr = ctx->request.get()->toString(); body["csr"] = csr; body["deviceName"] = ctx->deviceName; } auto request = std::make_shared<Request>( *Manager::instance().ioContext(), url, body, [ctx, w](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Auth] Got request callback with status code={} {}", response.status_code, response.body); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (response.status_code == 0 || this_ == nullptr) ctx->onFailure(AuthError::SERVER_ERROR, "Unable to connect to server"); else if (response.status_code >= 400 && response.status_code < 500) ctx->onFailure(AuthError::INVALID_ARGUMENTS, "Invalid credentials provided!"); else if (response.status_code < 200 || response.status_code > 299) ctx->onFailure(AuthError::INVALID_ARGUMENTS, ""); else { do { try { JAMI_WARNING("[Auth] Got server response: {}", response.body); auto cert = std::make_shared<dht::crypto::Certificate>( json["certificateChain"].asString()); auto accountCert = cert->issuer; if (not accountCert) { JAMI_ERR("[Auth] Unable to parse certificate: no issuer"); ctx->onFailure(AuthError::SERVER_ERROR, "Invalid certificate from server"); break; } auto receipt = json["deviceReceipt"].asString(); Json::Value receiptJson; std::string err; auto receiptReader = std::unique_ptr<Json::CharReader>( Json::CharReaderBuilder {}.newCharReader()); if (!receiptReader->parse(receipt.data(), receipt.data() + receipt.size(), &receiptJson, &err)) { JAMI_ERR("[Auth] Unable to parse receipt from server: %s", err.c_str()); ctx->onFailure(AuthError::SERVER_ERROR, "Unable to parse receipt from server"); break; } auto receiptSignature = base64::decode( json["receiptSignature"].asString()); auto info = std::make_unique<AccountInfo>(); info->identity.first = ctx->key.get(); info->identity.second = cert; info->devicePk = cert->getSharedPublicKey(); info->deviceId = info->devicePk->getLongId().toString(); info->accountId = accountCert->getId().toString(); info->contacts = std::make_unique<ContactList>(ctx->accountId, accountCert, this_->path_, this_->onChange_); // info->contacts->setContacts(a.contacts); if (ctx->deviceName.empty()) ctx->deviceName = info->deviceId.substr(8); info->contacts->foundAccountDevice(cert, ctx->deviceName, clock::now()); info->ethAccount = receiptJson["eth"].asString(); info->announce = parseAnnounce(receiptJson["announce"].asString(), info->accountId, info->devicePk->getId().toString()); if (not info->announce) { ctx->onFailure(AuthError::SERVER_ERROR, "Unable to parse announce from server"); return; } info->username = ctx->credentials->username; this_->creds_ = std::move(ctx->credentials); this_->info_ = std::move(info); std::map<std::string, std::string> config; for (auto itr = json.begin(); itr != json.end(); ++itr) { const auto& name = itr.name(); if (name == "nameServer"sv) { auto nameServer = json["nameServer"].asString(); if (!nameServer.empty() && nameServer[0] == '/') nameServer = this_->managerHostname_ + nameServer; this_->nameDir_ = NameDirectory::instance(nameServer); config .emplace(libjami::Account::ConfProperties::RingNS::URI, std::move(nameServer)); } else if (name == "userPhoto"sv) { this_->info_->photo = json["userPhoto"].asString(); } else { config.emplace(name, itr->asString()); } } ctx->onSuccess(*this_->info_, std::move(config), std::move(receipt), std::move(receiptSignature)); } catch (const std::exception& e) { JAMI_ERR("Error when loading account: %s", e.what()); ctx->onFailure(AuthError::NETWORK, ""); } } while (false); } if (auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock())) this_->clearRequest(response.request); }, this_->logger_); request->set_auth(ctx->credentials->username, ctx->credentials->password); this_->sendRequest(request); }); } void ServerAccountManager::onAuthEnded(const Json::Value& json, const dht::http::Response& response, TokenScope expectedScope) { if (response.status_code >= 200 && response.status_code < 300) { auto scopeStr = json["scope"].asString(); auto scope = scopeStr == "DEVICE"sv ? TokenScope::Device : (scopeStr == "USER"sv ? TokenScope::User : TokenScope::None); auto expires_in = json["expires_in"].asLargestUInt(); auto expiration = std::chrono::steady_clock::now() + std::chrono::seconds(expires_in); JAMI_WARNING("[Auth] Got server response: {} {}", response.status_code, response.body); setToken(json["access_token"].asString(), scope, expiration); } else { JAMI_WARNING("[Auth] Got server response: {} {}", response.status_code, response.body); authFailed(expectedScope, response.status_code); } clearRequest(response.request); } void ServerAccountManager::authenticateDevice() { if (not info_) { authFailed(TokenScope::Device, 0); } const std::string url = managerHostname_ + JAMI_PATH_LOGIN; JAMI_WARN("[Auth] Getting a device token: %s", url.c_str()); auto request = std::make_shared<Request>( *Manager::instance().ioContext(), url, Json::Value {Json::objectValue}, [w=weak_from_this()](Json::Value json, const dht::http::Response& response) { if (auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock())) this_->onAuthEnded(json, response, TokenScope::Device); }, logger_); request->set_identity(info_->identity); // request->set_certificate_authority(info_->identity.second->issuer->issuer); sendRequest(request); } void ServerAccountManager::authenticateAccount(const std::string& username, const std::string& password) { const std::string url = managerHostname_ + JAMI_PATH_LOGIN; JAMI_WARN("[Auth] Getting a device token: %s", url.c_str()); auto request = std::make_shared<Request>( *Manager::instance().ioContext(), url, Json::Value {Json::objectValue}, [w=weak_from_this()](Json::Value json, const dht::http::Response& response) { if (auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock())) this_->onAuthEnded(json, response, TokenScope::User); }, logger_); request->set_auth(username, password); sendRequest(request); } void ServerAccountManager::sendRequest(const std::shared_ptr<dht::http::Request>& request) { request->set_header_field(restinio::http_field_t::user_agent, "Jami"); { std::lock_guard lock(requestLock_); requests_.emplace(request); } request->send(); } void ServerAccountManager::clearRequest(const std::weak_ptr<dht::http::Request>& request) { if (auto req = request.lock()) { std::lock_guard lock(requestLock_); requests_.erase(req); } } void ServerAccountManager::authFailed(TokenScope scope, int code) { RequestQueue requests; { std::lock_guard lock(tokenLock_); requests = std::move(getRequestQueue(scope)); } JAMI_DEBUG("[Auth] Failed auth with scope {}, ending {} pending requests", (int) scope, requests.size()); if (code == 401) { // NOTE: we do not login every time to the server but retrieve a device token to use the account // If authentificate device fails with 401 // it means that the device is revoked if (onNeedsMigration_) onNeedsMigration_(); } while (not requests.empty()) { auto req = std::move(requests.front()); requests.pop(); req->terminate(code == 0 ? asio::error::not_connected : asio::error::access_denied); } } void ServerAccountManager::authError(TokenScope scope) { { std::lock_guard lock(tokenLock_); if (scope <= tokenScope_) { token_ = {}; tokenScope_ = TokenScope::None; } } if (scope == TokenScope::Device) authenticateDevice(); } void ServerAccountManager::setToken(std::string token, TokenScope scope, std::chrono::steady_clock::time_point expiration) { std::lock_guard lock(tokenLock_); token_ = std::move(token); tokenScope_ = scope; tokenExpire_ = expiration; nameDir_.get().setToken(token_); if (not token_.empty() and scope != TokenScope::None) { auto& reqQueue = getRequestQueue(scope); JAMI_DBG("[Auth] Got token with scope %d, handling %zu pending requests", (int) scope, reqQueue.size()); while (not reqQueue.empty()) { auto req = std::move(reqQueue.front()); reqQueue.pop(); setAuthHeaderFields(*req); sendRequest(req); } } } void ServerAccountManager::sendDeviceRequest(const std::shared_ptr<dht::http::Request>& req) { std::lock_guard lock(tokenLock_); if (hasAuthorization(TokenScope::Device)) { setAuthHeaderFields(*req); sendRequest(req); } else { auto& rQueue = getRequestQueue(TokenScope::Device); if (rQueue.empty()) authenticateDevice(); rQueue.emplace(req); } } void ServerAccountManager::sendAccountRequest(const std::shared_ptr<dht::http::Request>& req, const std::string& pwd) { std::lock_guard lock(tokenLock_); if (hasAuthorization(TokenScope::User)) { setAuthHeaderFields(*req); sendRequest(req); } else { auto& rQueue = getRequestQueue(TokenScope::User); if (rQueue.empty()) authenticateAccount(info_->username, pwd); rQueue.emplace(req); } } void ServerAccountManager::syncDevices() { const std::string urlDevices = managerHostname_ + PATH_DEVICES; const std::string urlContacts = managerHostname_ + PATH_CONTACTS; const std::string urlConversations = managerHostname_ + PATH_CONVERSATIONS; const std::string urlConversationsRequests = managerHostname_ + PATH_CONVERSATIONS_REQUESTS; JAMI_WARNING("[Auth] Sync conversations {}", urlConversations); Json::Value jsonConversations(Json::arrayValue); for (const auto& [key, convInfo] : ConversationModule::convInfos(accountId_)) { jsonConversations.append(convInfo.toJson()); } sendDeviceRequest(std::make_shared<Request>( *Manager::instance().ioContext(), urlConversations, jsonConversations, [w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Auth] Got conversation sync request callback with status code={}", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { JAMI_WARNING("[Auth] Got server response: {}", response.body); if (not json.isArray()) { JAMI_ERROR("[Auth] Unable to parse server response: not an array"); } else { SyncMsg convs; for (unsigned i = 0, n = json.size(); i < n; i++) { const auto& e = json[i]; auto ci = ConvInfo(e); convs.c[ci.id] = std::move(ci); } dht::ThreadPool::io().run([accountId=this_->accountId_, convs] { if (auto acc = Manager::instance().getAccount<JamiAccount>(accountId)) { acc->convModule()->onSyncData(convs, "", ""); } }); } } catch (const std::exception& e) { JAMI_ERROR("Error when iterating conversation list: {}", e.what()); } } else if (response.status_code == 401) this_->authError(TokenScope::Device); this_->clearRequest(response.request); }, logger_)); JAMI_WARNING("[Auth] Sync conversations requests {}", urlConversationsRequests); Json::Value jsonConversationsRequests(Json::arrayValue); for (const auto& [key, convRequest] : ConversationModule::convRequests(accountId_)) { auto jsonConversation = convRequest.toJson(); jsonConversationsRequests.append(std::move(jsonConversation)); } sendDeviceRequest(std::make_shared<Request>( *Manager::instance().ioContext(), urlConversationsRequests, jsonConversationsRequests, [w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Auth] Got conversations requests sync request callback with status code={}", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { JAMI_WARNING("[Auth] Got server response: {}", response.body); if (not json.isArray()) { JAMI_ERROR("[Auth] Unable to parse server response: not an array"); } else { SyncMsg convReqs; for (unsigned i = 0, n = json.size(); i < n; i++) { const auto& e = json[i]; auto cr = ConversationRequest(e); convReqs.cr[cr.conversationId] = std::move(cr); } dht::ThreadPool::io().run([accountId=this_->accountId_, convReqs] { if (auto acc = Manager::instance().getAccount<JamiAccount>(accountId)) { acc->convModule()->onSyncData(convReqs, "", ""); } }); } } catch (const std::exception& e) { JAMI_ERROR("Error when iterating conversations requests list: {}", e.what()); } } else if (response.status_code == 401) this_->authError(TokenScope::Device); this_->clearRequest(response.request); }, logger_)); JAMI_WARNING("[Auth] syncContacts {}", urlContacts); Json::Value jsonContacts(Json::arrayValue); for (const auto& contact : info_->contacts->getContacts()) { auto jsonContact = contact.second.toJson(); jsonContact["uri"] = contact.first.toString(); jsonContacts.append(std::move(jsonContact)); } sendDeviceRequest(std::make_shared<Request>( *Manager::instance().ioContext(), urlContacts, jsonContacts, [w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Auth] Got contact sync request callback with status code={}", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { JAMI_WARNING("[Auth] Got server response: {}", response.body); if (not json.isArray()) { JAMI_ERROR("[Auth] Unable to parse server response: not an array"); } else { for (unsigned i = 0, n = json.size(); i < n; i++) { const auto& e = json[i]; Contact contact(e); this_->info_->contacts ->updateContact(dht::InfoHash {e["uri"].asString()}, contact); } this_->info_->contacts->saveContacts(); } } catch (const std::exception& e) { JAMI_ERROR("Error when iterating contact list: {}", e.what()); } } else if (response.status_code == 401) this_->authError(TokenScope::Device); this_->clearRequest(response.request); }, logger_)); JAMI_WARNING("[Auth] syncDevices {}", urlDevices); sendDeviceRequest(std::make_shared<Request>( *Manager::instance().ioContext(), urlDevices, [w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Auth] Got request callback with status code={}", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { JAMI_WARNING("[Auth] Got server response: {}", response.body); if (not json.isArray()) { JAMI_ERROR("[Auth] Unable to parse server response: not an array"); } else { for (unsigned i = 0, n = json.size(); i < n; i++) { const auto& e = json[i]; dht::PkId deviceId(e["deviceId"].asString()); if (deviceId) { this_->info_->contacts->foundAccountDevice(deviceId, e["alias"].asString(), clock::now()); } } } } catch (const std::exception& e) { JAMI_ERROR("Error when iterating device list: {}", e.what()); } } else if (response.status_code == 401) this_->authError(TokenScope::Device); this_->clearRequest(response.request); }, logger_)); } void ServerAccountManager::syncBlueprintConfig(SyncBlueprintCallback onSuccess) { auto syncBlueprintCallback = std::make_shared<SyncBlueprintCallback>(onSuccess); const std::string urlBlueprints = managerHostname_ + PATH_BLUEPRINT; JAMI_DEBUG("[Auth] Synchronize blueprint configuration {}", urlBlueprints); sendDeviceRequest(std::make_shared<Request>( *Manager::instance().ioContext(), urlBlueprints, [syncBlueprintCallback, w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Auth] Got sync request callback with status code={}", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { std::map<std::string, std::string> config; for (auto itr = json.begin(); itr != json.end(); ++itr) { const auto& name = itr.name(); config.emplace(name, itr->asString()); } (*syncBlueprintCallback)(config); } catch (const std::exception& e) { JAMI_ERROR("Error when iterating blueprint config json: {}", e.what()); } } else if (response.status_code == 401) this_->authError(TokenScope::Device); this_->clearRequest(response.request); }, logger_)); } bool ServerAccountManager::revokeDevice(const std::string& device, std::string_view scheme, const std::string& password, RevokeDeviceCallback cb) { if (not info_ || scheme != fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD) { if (cb) cb(RevokeDeviceResult::ERROR_CREDENTIALS); return false; } const std::string url = managerHostname_ + PATH_DEVICE + "/" + device; JAMI_WARNING("[Revoke] Revoking device of {} at {}", info_->username, url); auto request = std::make_shared<Request>( *Manager::instance().ioContext(), url, [cb, w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DEBUG("[Revoke] Got request callback with status code={}", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { JAMI_WARNING("[Revoke] Got server response"); if (json["errorDetails"].empty()) { if (cb) cb(RevokeDeviceResult::SUCCESS); this_->syncDevices(); } } catch (const std::exception& e) { JAMI_ERROR("Error when loading device list: {}", e.what()); } } else if (cb) cb(RevokeDeviceResult::ERROR_NETWORK); this_->clearRequest(response.request); }, logger_); request->set_method(restinio::http_method_delete()); sendAccountRequest(request, password); return false; } void ServerAccountManager::registerName(const std::string& name, std::string_view scheme, const std::string&, RegistrationCallback cb) { cb(NameDirectory::RegistrationResponse::unsupported, name); } bool ServerAccountManager::searchUser(const std::string& query, SearchCallback cb) { const std::string url = managerHostname_ + PATH_SEARCH + "?queryString=" + query; JAMI_WARNING("[Search] Searching user {} at {}", query, url); sendDeviceRequest(std::make_shared<Request>( *Manager::instance().ioContext(), url, [cb, w=weak_from_this()](Json::Value json, const dht::http::Response& response) { JAMI_DBG("[Search] Got request callback with status code=%u", response.status_code); auto this_ = std::static_pointer_cast<ServerAccountManager>(w.lock()); if (!this_) return; if (response.status_code >= 200 && response.status_code < 300) { try { const auto& profiles = json["profiles"]; Json::Value::ArrayIndex rcount = profiles.size(); std::vector<std::map<std::string, std::string>> results; results.reserve(rcount); JAMI_WARNING("[Search] Got server response: {}", response.body); for (Json::Value::ArrayIndex i = 0; i < rcount; i++) { const auto& ruser = profiles[i]; std::map<std::string, std::string> user; for (const auto& member : ruser.getMemberNames()) { const auto& rmember = ruser[member]; if (rmember.isString()) user[member] = rmember.asString(); } results.emplace_back(std::move(user)); } if (cb) cb(results, SearchResponse::found); } catch (const std::exception& e) { JAMI_ERROR("[Search] Error during search: {}", e.what()); } } else { if (response.status_code == 401) this_->authError(TokenScope::Device); if (cb) cb({}, SearchResponse::error); } this_->clearRequest(response.request); }, logger_)); return true; } } // namespace jami
30,967
C++
.cpp
638
33.484326
129
0.525918
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,804
sync_module.cpp
savoirfairelinux_jami-daemon/src/jamidht/sync_module.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sync_module.h" #include "jamidht/conversation_module.h" #include "jamidht/archive_account_manager.h" #include <dhtnet/multiplexed_socket.h> namespace jami { class SyncModule::Impl : public std::enable_shared_from_this<Impl> { public: Impl(std::weak_ptr<JamiAccount>&& account); std::weak_ptr<JamiAccount> account_; // Sync connections std::recursive_mutex syncConnectionsMtx_; std::map<DeviceId /* deviceId */, std::vector<std::shared_ptr<dhtnet::ChannelSocket>>> syncConnections_; /** * Build SyncMsg and send it on socket * @param socket */ void syncInfos(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const std::shared_ptr<SyncMsg>& syncMsg); void onChannelShutdown(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const DeviceId& device); }; SyncModule::Impl::Impl(std::weak_ptr<JamiAccount>&& account) : account_(account) {} void SyncModule::Impl::syncInfos(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const std::shared_ptr<SyncMsg>& syncMsg) { auto acc = account_.lock(); if (!acc) return; msgpack::sbuffer buffer(UINT16_MAX); // Use max pkt size std::error_code ec; if (!syncMsg) { // Send contacts infos // This message can be big. TODO rewrite to only take UINT16_MAX bytes max or split it multiple // messages. For now, write 3 messages (UINT16_MAX*3 should be enough for all information). if (auto info = acc->accountManager()->getInfo()) { if (info->contacts) { SyncMsg msg; msg.ds = info->contacts->getSyncData(); msgpack::pack(buffer, msg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{:s}", ec.message()); return; } } } buffer.clear(); // Sync conversations auto c = ConversationModule::convInfos(acc->getAccountID()); if (!c.empty()) { SyncMsg msg; msg.c = std::move(c); msgpack::pack(buffer, msg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{:s}", ec.message()); return; } } buffer.clear(); // Sync requests auto cr = ConversationModule::convRequests(acc->getAccountID()); if (!cr.empty()) { SyncMsg msg; msg.cr = std::move(cr); msgpack::pack(buffer, msg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{:s}", ec.message()); return; } } auto convModule = acc->convModule(true); if (!convModule) return; // Sync conversation's preferences auto p = convModule->convPreferences(); if (!p.empty()) { SyncMsg msg; msg.p = std::move(p); msgpack::pack(buffer, msg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{:s}", ec.message()); return; } } buffer.clear(); // Sync read's status auto ms = convModule->convMessageStatus(); if (!ms.empty()) { SyncMsg msg; msg.ms = std::move(ms); msgpack::pack(buffer, msg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{:s}", ec.message()); return; } } buffer.clear(); } else { msgpack::pack(buffer, *syncMsg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) JAMI_ERROR("{:s}", ec.message()); } } //////////////////////////////////////////////////////////////// SyncModule::SyncModule(std::weak_ptr<JamiAccount>&& account) : pimpl_ {std::make_shared<Impl>(std::move(account))} {} void SyncModule::Impl::onChannelShutdown(const std::shared_ptr<dhtnet::ChannelSocket>& socket, const DeviceId& device) { std::lock_guard lk(syncConnectionsMtx_); auto connectionsIt = syncConnections_.find(device); if (connectionsIt == syncConnections_.end()) return; auto& connections = connectionsIt->second; auto conn = std::find(connections.begin(), connections.end(), socket); if (conn != connections.end()) connections.erase(conn); if (connections.empty()) syncConnections_.erase(connectionsIt); } void SyncModule::cacheSyncConnection(std::shared_ptr<dhtnet::ChannelSocket>&& socket, const std::string& peerId, const DeviceId& device) { std::lock_guard lk(pimpl_->syncConnectionsMtx_); pimpl_->syncConnections_[device].emplace_back(socket); socket->onShutdown([w = pimpl_->weak_from_this(), device, s=std::weak_ptr(socket)]() { if (auto shared = w.lock()) shared->onChannelShutdown(s.lock(), device); }); struct DecodingContext { msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t, void*) { return true; }, nullptr, 512}; }; socket->setOnRecv([acc = pimpl_->account_.lock(), device, peerId, ctx = std::make_shared<DecodingContext>() ](const uint8_t* buf, size_t len) { if (!buf || !acc) return len; ctx->pac.reserve_buffer(len); std::copy_n(buf, len, ctx->pac.buffer()); ctx->pac.buffer_consumed(len); msgpack::object_handle oh; try { while (ctx->pac.next(oh)) { SyncMsg msg; oh.get().convert(msg); if (auto manager = acc->accountManager()) manager->onSyncData(std::move(msg.ds), false); if (!msg.c.empty() || !msg.cr.empty() || !msg.p.empty() || !msg.ld.empty() || !msg.ms.empty()) if (auto cm = acc->convModule(true)) cm->onSyncData(msg, peerId, device.toString()); } } catch (const std::exception& e) { JAMI_WARNING("[convInfo] error on sync: {:s}", e.what()); } return len; }); pimpl_->syncInfos(socket, nullptr); } bool SyncModule::isConnected(const DeviceId& deviceId) const { std::lock_guard lk(pimpl_->syncConnectionsMtx_); auto it = pimpl_->syncConnections_.find(deviceId); if (it == pimpl_->syncConnections_.end()) return false; return !it->second.empty(); } void SyncModule::syncWithConnected(const std::shared_ptr<SyncMsg>& syncMsg, const DeviceId& deviceId) { std::lock_guard lk(pimpl_->syncConnectionsMtx_); for (auto& [did, sockets] : pimpl_->syncConnections_) { if (not sockets.empty()) { if (!deviceId || deviceId == did) { pimpl_->syncInfos(sockets[0], syncMsg); } } } } } // namespace jami
8,161
C++
.cpp
212
29.523585
113
0.573628
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,805
namedirectory.cpp
savoirfairelinux_jami-daemon/src/jamidht/namedirectory.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "namedirectory.h" #include "logger.h" #include "string_utils.h" #include "fileutils.h" #include "base64.h" #include "scheduled_executor.h" #include <asio.hpp> #include "manager.h" #include <opendht/crypto.h> #include <opendht/utils.h> #include <opendht/http.h> #include <opendht/logger.h> #include <opendht/thread_pool.h> #include <cstddef> #include <msgpack.hpp> #include <json/json.h> /* for visual studio */ #include <ciso646> #include <sstream> #include <regex> #include <fstream> namespace jami { constexpr const char* const QUERY_NAME {"/name/"}; constexpr const char* const QUERY_ADDR {"/addr/"}; constexpr auto CACHE_DIRECTORY {"namecache"sv}; constexpr const char DEFAULT_SERVER_HOST[] = "https://ns.jami.net"; const std::string HEX_PREFIX = "0x"; constexpr std::chrono::seconds SAVE_INTERVAL {5}; /** Parser for URIs. ( protocol ) ( username ) ( hostname ) */ const std::regex URI_VALIDATOR { "^([a-zA-Z]+:(?://)?)?(?:([a-z0-9-_]{1,64})@)?([a-zA-Z0-9\\-._~%!$&'()*+,;=:\\[\\]]+)"}; const std::regex NAME_VALIDATOR {"^[a-zA-Z0-9-_]{3,32}$"}; constexpr size_t MAX_RESPONSE_SIZE {1024ul * 1024}; using Request = dht::http::Request; void toLower(std::string& string) { std::transform(string.begin(), string.end(), string.begin(), ::tolower); } NameDirectory& NameDirectory::instance() { return instance(DEFAULT_SERVER_HOST); } void NameDirectory::lookupUri(std::string_view uri, const std::string& default_server, LookupCallback cb) { const std::string& default_ns = default_server.empty() ? DEFAULT_SERVER_HOST : default_server; std::svmatch pieces_match; if (std::regex_match(uri, pieces_match, URI_VALIDATOR)) { if (pieces_match.size() == 4) { if (pieces_match[2].length() == 0) instance(default_ns).lookupName(pieces_match[3], std::move(cb)); else instance(pieces_match[3].str()).lookupName(pieces_match[2], std::move(cb)); return; } } JAMI_ERROR("Unable to parse URI: {}", uri); cb("", Response::invalidResponse); } NameDirectory::NameDirectory(const std::string& serverUrl, std::shared_ptr<dht::Logger> l) : serverUrl_(serverUrl) , logger_(std::move(l)) , httpContext_(Manager::instance().ioContext()) { if (!serverUrl_.empty() && serverUrl_.back() == '/') serverUrl_.pop_back(); resolver_ = std::make_shared<dht::http::Resolver>(*httpContext_, serverUrl, logger_); cachePath_ = fileutils::get_cache_dir() / CACHE_DIRECTORY / resolver_->get_url().host; } NameDirectory::~NameDirectory() { decltype(requests_) requests; { std::lock_guard lk(requestsMtx_); requests = std::move(requests_); } for (auto& req : requests) req->cancel(); } void NameDirectory::load() { loadCache(); } NameDirectory& NameDirectory::instance(const std::string& serverUrl, std::shared_ptr<dht::Logger> l) { const std::string& s = serverUrl.empty() ? DEFAULT_SERVER_HOST : serverUrl; static std::mutex instanceMtx {}; std::lock_guard lock(instanceMtx); static std::map<std::string, NameDirectory> instances {}; auto it = instances.find(s); if (it != instances.end()) return it->second; auto r = instances.emplace(std::piecewise_construct, std::forward_as_tuple(s), std::forward_as_tuple(s, l)); if (r.second) r.first->second.load(); return r.first->second; } void NameDirectory::setHeaderFields(Request& request) { request.set_header_field(restinio::http_field_t::user_agent, fmt::format("Jami ({}/{})", jami::platform(), jami::arch())); request.set_header_field(restinio::http_field_t::accept, "*/*"); request.set_header_field(restinio::http_field_t::content_type, "application/json"); } void NameDirectory::lookupAddress(const std::string& addr, LookupCallback cb) { auto cacheResult = nameCache(addr); if (not cacheResult.empty()) { cb(cacheResult, Response::found); return; } auto request = std::make_shared<Request>(*httpContext_, resolver_, serverUrl_ + QUERY_ADDR + addr); try { request->set_method(restinio::http_method_get()); setHeaderFields(*request); request->add_on_done_callback( [this, cb = std::move(cb), addr](const dht::http::Response& response) { if (response.status_code >= 400 && response.status_code < 500) { auto cacheResult = nameCache(addr); if (not cacheResult.empty()) cb(cacheResult, Response::found); else cb("", Response::notFound); } else if (response.status_code != 200) { JAMI_ERROR("Address lookup for {} failed with code={}", addr, response.status_code); cb("", Response::error); } else { try { Json::Value json; std::string err; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(response.body.data(), response.body.data() + response.body.size(), &json, &err)) { JAMI_DBG("Address lookup for %s: Unable to parse server response: %s", addr.c_str(), response.body.c_str()); cb("", Response::error); return; } auto name = json["name"].asString(); if (name.empty()) { cb(name, Response::notFound); return; } JAMI_DEBUG("Found name for {}: {}", addr, name); { std::lock_guard l(cacheLock_); addrCache_.emplace(name, addr); nameCache_.emplace(addr, name); } cb(name, Response::found); scheduleCacheSave(); } catch (const std::exception& e) { JAMI_ERROR("Error when performing address lookup: {}", e.what()); cb("", Response::error); } } std::lock_guard lk(requestsMtx_); if (auto req = response.request.lock()) requests_.erase(req); }); { std::lock_guard lk(requestsMtx_); requests_.emplace(request); } request->send(); } catch (const std::exception& e) { JAMI_ERROR("Error when performing address lookup: {}", e.what()); std::lock_guard lk(requestsMtx_); if (request) requests_.erase(request); } } bool NameDirectory::verify(const std::string& name, const dht::crypto::PublicKey& pk, const std::string& signature) { return pk.checkSignature(std::vector<uint8_t>(name.begin(), name.end()), base64::decode(signature)); } void NameDirectory::lookupName(const std::string& n, LookupCallback cb) { std::string name {n}; if (not validateName(name)) { cb("", Response::invalidResponse); return; } toLower(name); std::string cacheResult = addrCache(name); if (not cacheResult.empty()) { cb(cacheResult, Response::found); return; } auto request = std::make_shared<Request>(*httpContext_, resolver_, serverUrl_ + QUERY_NAME + name); try { request->set_method(restinio::http_method_get()); setHeaderFields(*request); request->add_on_done_callback([this, name, cb = std::move(cb)]( const dht::http::Response& response) { if (response.status_code >= 400 && response.status_code < 500) cb("", Response::notFound); else if (response.status_code < 200 || response.status_code > 299) cb("", Response::error); else { try { Json::Value json; std::string err; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(response.body.data(), response.body.data() + response.body.size(), &json, &err)) { JAMI_ERROR("Name lookup for {}: Unable to parse server response: {}", name, response.body); cb("", Response::error); return; } auto addr = json["addr"].asString(); auto publickey = json["publickey"].asString(); auto signature = json["signature"].asString(); if (!addr.compare(0, HEX_PREFIX.size(), HEX_PREFIX)) addr = addr.substr(HEX_PREFIX.size()); if (addr.empty()) { cb("", Response::notFound); return; } if (not publickey.empty() and not signature.empty()) { try { auto pk = dht::crypto::PublicKey(base64::decode(publickey)); if (pk.getId().toString() != addr or not verify(name, pk, signature)) { cb("", Response::invalidResponse); return; } } catch (const std::exception& e) { cb("", Response::invalidResponse); return; } } JAMI_DEBUG("Found address for {}: {}", name, addr); { std::lock_guard l(cacheLock_); addrCache_.emplace(name, addr); nameCache_.emplace(addr, name); } cb(addr, Response::found); scheduleCacheSave(); } catch (const std::exception& e) { JAMI_ERROR("Error when performing name lookup: {}", e.what()); cb("", Response::error); } } if (auto req = response.request.lock()) requests_.erase(req); }); { std::lock_guard lk(requestsMtx_); requests_.emplace(request); } request->send(); } catch (const std::exception& e) { JAMI_ERROR("Name lookup for {} failed: {}", name, e.what()); std::lock_guard lk(requestsMtx_); if (request) requests_.erase(request); } } bool NameDirectory::validateName(const std::string& name) const { return std::regex_match(name, NAME_VALIDATOR); } using Blob = std::vector<uint8_t>; void NameDirectory::registerName(const std::string& addr, const std::string& n, const std::string& owner, RegistrationCallback cb, const std::string& signedname, const std::string& publickey) { std::string name {n}; if (not validateName(name)) { cb(RegistrationResponse::invalidName, name); return; } toLower(name); auto cacheResult = addrCache(name); if (not cacheResult.empty()) { if (cacheResult == addr) cb(RegistrationResponse::success, name); else cb(RegistrationResponse::alreadyTaken, name); return; } { std::lock_guard l(cacheLock_); if (not pendingRegistrations_.emplace(addr, name).second) { JAMI_WARNING("RegisterName: already registering name {} {}", addr, name); cb(RegistrationResponse::error, name); return; } } std::string body = fmt::format("{{\"addr\":\"{}\",\"owner\":\"{}\",\"signature\":\"{}\",\"publickey\":\"{}\"}}", addr, owner, signedname, base64::encode(publickey)); auto request = std::make_shared<Request>(*httpContext_, resolver_, serverUrl_ + QUERY_NAME + name); try { request->set_method(restinio::http_method_post()); setHeaderFields(*request); request->set_body(body); JAMI_WARNING("RegisterName: sending request {} {}", addr, name); request->add_on_done_callback( [this, name, addr, cb = std::move(cb)](const dht::http::Response& response) { { std::lock_guard l(cacheLock_); pendingRegistrations_.erase(name); } if (response.status_code == 400) { cb(RegistrationResponse::incompleteRequest, name); JAMI_ERROR("RegistrationResponse::incompleteRequest"); } else if (response.status_code == 401) { cb(RegistrationResponse::signatureVerificationFailed, name); JAMI_ERROR("RegistrationResponse::signatureVerificationFailed"); } else if (response.status_code == 403) { cb(RegistrationResponse::alreadyTaken, name); JAMI_ERROR("RegistrationResponse::alreadyTaken"); } else if (response.status_code == 409) { cb(RegistrationResponse::alreadyTaken, name); JAMI_ERROR("RegistrationResponse::alreadyTaken"); } else if (response.status_code > 400 && response.status_code < 500) { cb(RegistrationResponse::alreadyTaken, name); JAMI_ERROR("RegistrationResponse::alreadyTaken"); } else if (response.status_code < 200 || response.status_code > 299) { cb(RegistrationResponse::error, name); JAMI_ERROR("RegistrationResponse::error"); } else { Json::Value json; std::string err; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(response.body.data(), response.body.data() + response.body.size(), &json, &err)) { cb(RegistrationResponse::error, name); return; } auto success = json["success"].asBool(); JAMI_DEBUG("Got reply for registration of {} {}: {}", name, addr, success ? "success" : "failure"); if (success) { std::lock_guard l(cacheLock_); addrCache_.emplace(name, addr); nameCache_.emplace(addr, name); } cb(success ? RegistrationResponse::success : RegistrationResponse::error, name); } std::lock_guard lk(requestsMtx_); if (auto req = response.request.lock()) requests_.erase(req); }); { std::lock_guard lk(requestsMtx_); requests_.emplace(request); } request->send(); } catch (const std::exception& e) { JAMI_ERROR("Error when performing name registration: {}", e.what()); cb(RegistrationResponse::error, name); { std::lock_guard l(cacheLock_); pendingRegistrations_.erase(name); } std::lock_guard lk(requestsMtx_); if (request) requests_.erase(request); } } void NameDirectory::scheduleCacheSave() { // JAMI_DBG("Scheduling cache save to %s", cachePath_.c_str()); std::weak_ptr<Task> task = Manager::instance().scheduler().scheduleIn( [this] { dht::ThreadPool::io().run([this] { saveCache(); }); }, SAVE_INTERVAL); std::swap(saveTask_, task); if (auto old = task.lock()) old->cancel(); } void NameDirectory::saveCache() { dhtnet::fileutils::recursive_mkdir(fileutils::get_cache_dir() / CACHE_DIRECTORY); std::lock_guard lock(dhtnet::fileutils::getFileLock(cachePath_)); std::ofstream file(cachePath_, std::ios::trunc | std::ios::binary); { std::lock_guard l(cacheLock_); msgpack::pack(file, nameCache_); } JAMI_DEBUG("Saved {:d} name-address mappings to {}", nameCache_.size(), cachePath_); } void NameDirectory::loadCache() { msgpack::unpacker pac; // read file { std::lock_guard lock(dhtnet::fileutils::getFileLock(cachePath_)); std::ifstream file(cachePath_); if (!file.is_open()) { JAMI_DEBUG("Unable to load {}", cachePath_); return; } std::string line; while (std::getline(file, line)) { pac.reserve_buffer(line.size()); memcpy(pac.buffer(), line.data(), line.size()); pac.buffer_consumed(line.size()); } } // load values std::lock_guard l(cacheLock_); msgpack::object_handle oh; if (pac.next(oh)) oh.get().convert(nameCache_); for (const auto& m : nameCache_) addrCache_.emplace(m.second, m.first); JAMI_DEBUG("Loaded {:d} name-address mappings", nameCache_.size()); } } // namespace jami
19,170
C++
.cpp
472
28.370763
116
0.524756
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,806
jamiaccount.cpp
savoirfairelinux_jami-daemon/src/jamidht/jamiaccount.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "jamiaccount.h" #include "logger.h" #include "accountarchive.h" #include "jami_contact.h" #include "configkeys.h" #include "contact_list.h" #include "archive_account_manager.h" #include "server_account_manager.h" #include "jamidht/channeled_transport.h" #include "conversation_channel_handler.h" #include "sync_channel_handler.h" #include "message_channel_handler.h" #include "transfer_channel_handler.h" #include "swarm/swarm_channel_handler.h" #include "jami/media_const.h" #include "sip/sdp.h" #include "sip/sipvoiplink.h" #include "sip/sipcall.h" #include "sip/siptransport.h" #include "connectivity/sip_utils.h" #include "uri.h" #include "client/ring_signal.h" #include "jami/call_const.h" #include "jami/account_const.h" #include "system_codec_container.h" #include "account_schema.h" #include "manager.h" #include "connectivity/utf8_utils.h" #include "connectivity/ip_utils.h" #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #include "plugin/chatservicesmanager.h" #endif #ifdef ENABLE_VIDEO #include "libav_utils.h" #endif #include "fileutils.h" #include "string_utils.h" #include "archiver.h" #include "data_transfer.h" #include "libdevcrypto/Common.h" #include "base64.h" #include "vcard.h" #include "im/instant_messaging.h" #include <dhtnet/ice_transport.h> #include <dhtnet/ice_transport_factory.h> #include <dhtnet/upnp/upnp_control.h> #include <dhtnet/multiplexed_socket.h> #include <dhtnet/certstore.h> #include <opendht/thread_pool.h> #include <opendht/peer_discovery.h> #include <opendht/http.h> #include <yaml-cpp/yaml.h> #include <unistd.h> #include <algorithm> #include <array> #include <cctype> #include <charconv> #include <cinttypes> #include <cstdarg> #include <initializer_list> #include <memory> #include <regex> #include <sstream> #include <string> #include <system_error> using namespace std::placeholders; namespace jami { constexpr pj_str_t STR_MESSAGE_ID = jami::sip_utils::CONST_PJ_STR("Message-ID"); static constexpr const char MIME_TYPE_IMDN[] {"message/imdn+xml"}; static constexpr const char MIME_TYPE_PIDF[] {"application/pidf+xml"}; static constexpr const char MIME_TYPE_INVITE_JSON[] {"application/invite+json"}; static constexpr const char DEVICE_ID_PATH[] {"ring_device"}; static constexpr auto TREATED_PATH = "treatedImMessages"sv; // Used to pass infos to a pjsip callback (pjsip_endpt_send_request) struct TextMessageCtx { std::weak_ptr<JamiAccount> acc; std::string to; DeviceId deviceId; uint64_t id; bool retryOnTimeout; std::shared_ptr<dhtnet::ChannelSocket> channel; bool onlyConnected; }; struct VCardMessageCtx { std::shared_ptr<std::atomic_int> success; int total; std::string path; }; namespace Migration { enum class State { // Contains all the Migration states SUCCESS, INVALID }; std::string mapStateNumberToString(const State migrationState) { #define CASE_STATE(X) \ case Migration::State::X: \ return #X switch (migrationState) { CASE_STATE(INVALID); CASE_STATE(SUCCESS); } return {}; } void setState(const std::string& accountID, const State migrationState) { emitSignal<libjami::ConfigurationSignal::MigrationEnded>(accountID, mapStateNumberToString(migrationState)); } } // namespace Migration struct JamiAccount::BuddyInfo { /* the buddy id */ dht::InfoHash id; /* number of devices connected on the DHT */ uint32_t devices_cnt {}; /* The disposable object to update buddy info */ std::future<size_t> listenToken; BuddyInfo(dht::InfoHash id) : id(id) {} }; struct JamiAccount::PendingCall { std::chrono::steady_clock::time_point start; std::shared_ptr<IceTransport> ice_sp; std::shared_ptr<IceTransport> ice_tcp_sp; std::weak_ptr<SIPCall> call; std::future<size_t> listen_key; dht::InfoHash call_key; dht::InfoHash from; dht::InfoHash from_account; std::shared_ptr<dht::crypto::Certificate> from_cert; }; struct JamiAccount::PendingMessage { std::set<DeviceId> to; }; struct AccountPeerInfo { dht::InfoHash accountId; std::string displayName; MSGPACK_DEFINE(accountId, displayName) }; struct JamiAccount::DiscoveredPeer { std::string displayName; std::shared_ptr<Task> cleanupTask; }; static constexpr const char* const RING_URI_PREFIX = "ring:"; static constexpr const char* const JAMI_URI_PREFIX = "jami:"; static const auto PROXY_REGEX = std::regex( "(https?://)?([\\w\\.\\-_\\~]+)(:(\\d+)|:\\[(.+)-(.+)\\])?"); static const std::string PEER_DISCOVERY_JAMI_SERVICE = "jami"; const constexpr auto PEER_DISCOVERY_EXPIRATION = std::chrono::minutes(1); using ValueIdDist = std::uniform_int_distribution<dht::Value::Id>; static std::string_view stripPrefix(std::string_view toUrl) { auto dhtf = toUrl.find(RING_URI_PREFIX); if (dhtf != std::string_view::npos) { dhtf = dhtf + 5; } else { dhtf = toUrl.find(JAMI_URI_PREFIX); if (dhtf != std::string_view::npos) { dhtf = dhtf + 5; } else { dhtf = toUrl.find("sips:"); dhtf = (dhtf == std::string_view::npos) ? 0 : dhtf + 5; } } while (dhtf < toUrl.length() && toUrl[dhtf] == '/') dhtf++; return toUrl.substr(dhtf); } static std::string_view parseJamiUri(std::string_view toUrl) { auto sufix = stripPrefix(toUrl); if (sufix.length() < 40) throw std::invalid_argument("id must be a Jami infohash"); const std::string_view toUri = sufix.substr(0, 40); if (std::find_if_not(toUri.cbegin(), toUri.cend(), ::isxdigit) != toUri.cend()) throw std::invalid_argument("id must be a Jami infohash"); return toUri; } static constexpr const char* dhtStatusStr(dht::NodeStatus status) { return status == dht::NodeStatus::Connected ? "connected" : (status == dht::NodeStatus::Connecting ? "connecting" : "disconnected"); } JamiAccount::JamiAccount(const std::string& accountId) : SIPAccountBase(accountId) , idPath_(fileutils::get_data_dir() / accountId) , cachePath_(fileutils::get_cache_dir() / accountId) , dataPath_(cachePath_ / "values") , certStore_ {std::make_unique<dhtnet::tls::CertificateStore>(idPath_, Logger::dhtLogger())} , dht_(new dht::DhtRunner) , treatedMessages_(cachePath_ / TREATED_PATH) , connectionManager_ {} , nonSwarmTransferManager_() {} JamiAccount::~JamiAccount() noexcept { if (dht_) dht_->join(); } void JamiAccount::shutdownConnections() { JAMI_DBG("[Account %s] Shutdown connections", getAccountID().c_str()); decltype(gitServers_) gservers; { std::lock_guard lk(gitServersMtx_); gservers = std::move(gitServers_); } for (auto& [_id, gs] : gservers) gs->stop(); { std::lock_guard lk(connManagerMtx_); // Just move destruction on another thread. dht::ThreadPool::io().run([conMgr = std::make_shared<decltype(connectionManager_)>( std::move(connectionManager_))] {}); connectionManager_.reset(); channelHandlers_.clear(); } if (convModule_) { convModule_->shutdownConnections(); } std::lock_guard lk(sipConnsMtx_); sipConns_.clear(); } void JamiAccount::flush() { // Class base method SIPAccountBase::flush(); dhtnet::fileutils::removeAll(cachePath_); dhtnet::fileutils::removeAll(dataPath_); dhtnet::fileutils::removeAll(idPath_, true); } std::shared_ptr<SIPCall> JamiAccount::newIncomingCall(const std::string& from, const std::vector<libjami::MediaMap>& mediaList, const std::shared_ptr<SipTransport>& sipTransp) { JAMI_DEBUG("New incoming call from {:s} with {:d} media", from, mediaList.size()); if (sipTransp) { auto call = Manager::instance().callFactory.newSipCall(shared(), Call::CallType::INCOMING, mediaList); call->setPeerUri(JAMI_URI_PREFIX + from); call->setPeerNumber(from); call->setSipTransport(sipTransp, getContactHeader(sipTransp)); return call; } JAMI_ERR("newIncomingCall: unable to find matching call for %s", from.c_str()); return nullptr; } std::shared_ptr<Call> JamiAccount::newOutgoingCall(std::string_view toUrl, const std::vector<libjami::MediaMap>& mediaList) { auto uri = Uri(toUrl); if (uri.scheme() == Uri::Scheme::SWARM || uri.scheme() == Uri::Scheme::RENDEZVOUS) { // NOTE: In this case newOutgoingCall can act as "unholdConference" and just attach the // host to the current hosted conference. So, no call will be returned in that case. return newSwarmOutgoingCallHelper(uri, mediaList); } auto& manager = Manager::instance(); std::shared_ptr<SIPCall> call; // SIP allows sending empty invites, this use case is not used with Jami accounts. if (not mediaList.empty()) { call = manager.callFactory.newSipCall(shared(), Call::CallType::OUTGOING, mediaList); } else { JAMI_WARN("Media list is empty, setting a default list"); call = manager.callFactory.newSipCall(shared(), Call::CallType::OUTGOING, MediaAttribute::mediaAttributesToMediaMaps( createDefaultMediaList(isVideoEnabled()))); } if (not call) return {}; connectionManager_->getIceOptions([call, w = weak(), uri = std::move(uri)](auto&& opts) { if (call->isIceEnabled()) { if (not call->createIceMediaTransport(false) or not call->initIceMediaTransport(true, std::forward<dhtnet::IceTransportOptions>(opts))) { return; } } auto shared = w.lock(); if (!shared) return; JAMI_DBG() << "New outgoing call with " << uri.toString(); call->setPeerNumber(uri.authority()); call->setPeerUri(uri.toString()); shared->newOutgoingCallHelper(call, uri); }); return call; } void JamiAccount::newOutgoingCallHelper(const std::shared_ptr<SIPCall>& call, const Uri& uri) { JAMI_DBG() << this << "Calling peer " << uri.authority(); try { startOutgoingCall(call, uri.authority()); } catch (...) { #if HAVE_RINGNS auto suffix = stripPrefix(uri.toString()); NameDirectory::lookupUri(suffix, config().nameServer, [wthis_ = weak(), call](const std::string& result, NameDirectory::Response response) { // we may run inside an unknown thread, but following code must // be called in main thread runOnMainThread([wthis_, result, response, call]() { if (response != NameDirectory::Response::found) { call->onFailure(EINVAL); return; } if (auto sthis = wthis_.lock()) { try { sthis->startOutgoingCall(call, result); } catch (...) { call->onFailure(ENOENT); } } else { call->onFailure(); } }); }); #else call->onFailure(ENOENT); #endif } } std::shared_ptr<SIPCall> JamiAccount::newSwarmOutgoingCallHelper(const Uri& uri, const std::vector<libjami::MediaMap>& mediaList) { JAMI_DEBUG("[Account {}] Calling conversation {}", getAccountID(), uri.authority()); return convModule()->call( uri.authority(), mediaList, [this, uri](const auto& accountUri, const auto& deviceId, const auto& call) { if (!call) return; std::unique_lock lkSipConn(sipConnsMtx_); for (auto& [key, value] : sipConns_) { if (key.first != accountUri || key.second != deviceId) continue; if (value.empty()) continue; auto& sipConn = value.back(); if (!sipConn.channel) { JAMI_WARN( "A SIP transport exists without Channel, this is a bug. Please report"); continue; } auto transport = sipConn.transport; if (!transport or !sipConn.channel) continue; call->setState(Call::ConnectionState::PROGRESSING); auto remoted_address = sipConn.channel->getRemoteAddress(); try { onConnectedOutgoingCall(call, uri.authority(), remoted_address); return; } catch (const VoipLinkException&) { // In this case, the main scenario is that SIPStartCall failed because // the ICE is dead and the TLS session didn't send any packet on that dead // link (connectivity change, killed by the os, etc) // Here, we don't need to do anything, the TLS will fail and will delete // the cached transport continue; } } lkSipConn.unlock(); { std::lock_guard lkP(pendingCallsMutex_); pendingCalls_[deviceId].emplace_back(call); } // Else, ask for a channel (for future calls/text messages) auto type = call->hasVideo() ? "videoCall" : "audioCall"; JAMI_WARNING("[call {}] No channeled socket with this peer. Send request", call->getCallId()); requestSIPConnection(accountUri, deviceId, type, true, call); }); } void JamiAccount::handleIncomingConversationCall(const std::string& callId, const std::string& destination) { auto split = jami::split_string(destination, '/'); if (split.size() != 4) return; auto conversationId = std::string(split[0]); auto accountUri = std::string(split[1]); auto deviceId = std::string(split[2]); auto confId = std::string(split[3]); if (getUsername() != accountUri || currentDeviceId() != deviceId) return; // Avoid concurrent checks in this part std::lock_guard lk(rdvMtx_); auto isNotHosting = !convModule()->isHosting(conversationId, confId); if (confId == "0") { auto currentCalls = convModule()->getActiveCalls(conversationId); if (!currentCalls.empty()) { confId = currentCalls[0]["id"]; isNotHosting = false; } else { confId = callId; JAMI_DEBUG("No active call to join, create conference"); } } auto preferences = convModule()->getConversationPreferences(conversationId); auto canHost = true; #if defined(__ANDROID__) || defined(__APPLE__) // By default, mobile devices SHOULD NOT host conferences. canHost = false; #endif auto itPref = preferences.find(ConversationPreferences::HOST_CONFERENCES); if (itPref != preferences.end()) { canHost = itPref->second == TRUE_STR; } auto call = getCall(callId); if (!call) { JAMI_ERROR("Call {} not found", callId); return; } if (isNotHosting && !canHost) { JAMI_DEBUG("Request for hosting a conference declined"); Manager::instance().hangupCall(getAccountID(), callId); return; } std::shared_ptr<Conference> conf; std::vector<libjami::MediaMap> currentMediaList; if (!isNotHosting) { conf = getConference(confId); if (!conf) { JAMI_ERROR("Conference {} not found", confId); return; } for (const auto& m : conf->currentMediaList()) { if (m.at(libjami::Media::MediaAttributeKey::MEDIA_TYPE) == libjami::Media::MediaAttributeValue::VIDEO && !call->hasVideo()) { continue; } currentMediaList.emplace_back(m); } } if (currentMediaList.empty()) { currentMediaList = MediaAttribute::mediaAttributesToMediaMaps( createDefaultMediaList(call->hasVideo(), true)); } Manager::instance().answerCall(*call, currentMediaList); if (isNotHosting) { JAMI_DEBUG("Creating conference for swarm {} with id {}", conversationId, confId); // Create conference and host it. convModule()->hostConference(conversationId, confId, callId); } else { JAMI_DEBUG("Adding participant {} for swarm {} with id {}", callId, conversationId, confId); Manager::instance().addAudio(*call); conf->addSubCall(callId); emitSignal<libjami::CallSignal::ConferenceChanged>(getAccountID(), conf->getConfId(), conf->getStateStr()); } } std::shared_ptr<SIPCall> JamiAccount::createSubCall(const std::shared_ptr<SIPCall>& mainCall) { auto mediaList = MediaAttribute::mediaAttributesToMediaMaps(mainCall->getMediaAttributeList()); return Manager::instance().callFactory.newSipCall(shared(), Call::CallType::OUTGOING, mediaList); } void JamiAccount::startOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& toUri) { if (not accountManager_ or not dht_) { call->onFailure(ENETDOWN); return; } // TODO: for now, we automatically trust all explicitly called peers setCertificateStatus(toUri, dhtnet::tls::TrustStore::PermissionStatus::ALLOWED); call->setState(Call::ConnectionState::TRYING); std::weak_ptr<SIPCall> wCall = call; #if HAVE_RINGNS accountManager_->lookupAddress(toUri, [wCall](const std::string& result, const NameDirectory::Response& response) { if (response == NameDirectory::Response::found) if (auto call = wCall.lock()) { call->setPeerRegisteredName(result); } }); #endif dht::InfoHash peer_account(toUri); // Call connected devices std::set<DeviceId> devices; std::unique_lock lkSipConn(sipConnsMtx_); // NOTE: dummyCall is a call used to avoid to mark the call as failed if the // cached connection is failing with ICE (close event still not detected). auto dummyCall = createSubCall(call); call->addSubCall(*dummyCall); dummyCall->setIceMedia(call->getIceMedia()); auto sendRequest = [this, wCall, toUri, dummyCall = std::move(dummyCall)](const DeviceId& deviceId, bool eraseDummy) { if (eraseDummy) { // Mark the temp call as failed to stop the main call if necessary if (dummyCall) dummyCall->onFailure(static_cast<int>(std::errc::no_such_device_or_address)); return; } auto call = wCall.lock(); if (not call) return; auto state = call->getConnectionState(); if (state != Call::ConnectionState::PROGRESSING and state != Call::ConnectionState::TRYING) return; auto dev_call = createSubCall(call); dev_call->setPeerNumber(call->getPeerNumber()); dev_call->setState(Call::ConnectionState::TRYING); call->addStateListener( [w = weak(), deviceId](Call::CallState, Call::ConnectionState state, int) { if (state != Call::ConnectionState::PROGRESSING and state != Call::ConnectionState::TRYING) { if (auto shared = w.lock()) shared->callConnectionClosed(deviceId, true); return false; } return true; }); call->addSubCall(*dev_call); dev_call->setIceMedia(call->getIceMedia()); { std::lock_guard lk(pendingCallsMutex_); pendingCalls_[deviceId].emplace_back(dev_call); } JAMI_WARNING("[call {}] No channeled socket with this peer. Send request", call->getCallId()); // Else, ask for a channel (for future calls/text messages) auto type = call->hasVideo() ? "videoCall" : "audioCall"; requestSIPConnection(toUri, deviceId, type, true, dev_call); }; std::vector<std::shared_ptr<dhtnet::ChannelSocket>> channels; for (auto& [key, value] : sipConns_) { if (key.first != toUri) continue; if (value.empty()) continue; auto& sipConn = value.back(); if (!sipConn.channel) { JAMI_WARNING("A SIP transport exists without Channel, this is a bug. Please report"); continue; } auto transport = sipConn.transport; auto remote_address = sipConn.channel->getRemoteAddress(); if (!transport or !remote_address) continue; channels.emplace_back(sipConn.channel); JAMI_WARNING("[call {}] A channeled socket is detected with this peer.", call->getCallId()); auto dev_call = createSubCall(call); dev_call->setPeerNumber(call->getPeerNumber()); dev_call->setSipTransport(transport, getContactHeader(transport)); call->addSubCall(*dev_call); dev_call->setIceMedia(call->getIceMedia()); // Set the call in PROGRESSING State because the ICE session // is already ready. Note that this line should be after // addSubcall() to change the state of the main call // and avoid to get an active call in a TRYING state. dev_call->setState(Call::ConnectionState::PROGRESSING); { std::lock_guard lk(onConnectionClosedMtx_); onConnectionClosed_[key.second] = sendRequest; } call->addStateListener( [w = weak(), deviceId = key.second](Call::CallState, Call::ConnectionState state, int) { if (state != Call::ConnectionState::PROGRESSING and state != Call::ConnectionState::TRYING) { if (auto shared = w.lock()) shared->callConnectionClosed(deviceId, true); return false; } return true; }); try { onConnectedOutgoingCall(dev_call, toUri, remote_address); } catch (const VoipLinkException&) { // In this case, the main scenario is that SIPStartCall failed because // the ICE is dead and the TLS session didn't send any packet on that dead // link (connectivity change, killed by the os, etc) // Here, we don't need to do anything, the TLS will fail and will delete // the cached transport continue; } devices.emplace(key.second); } lkSipConn.unlock(); // Note: Send beacon can destroy the socket (if storing last occurence of shared_ptr) // causing sipConn to be destroyed. So, do it while sipConns_ not locked. for (const auto& channel : channels) channel->sendBeacon(); // Find listening devices for this account accountManager_->forEachDevice( peer_account, [this, devices = std::move(devices), sendRequest]( const std::shared_ptr<dht::crypto::PublicKey>& dev) { // Test if already sent via a SIP transport auto deviceId = dev->getLongId(); if (devices.find(deviceId) != devices.end()) return; { std::lock_guard lk(onConnectionClosedMtx_); onConnectionClosed_[deviceId] = sendRequest; } sendRequest(deviceId, false); }, [wCall](bool ok) { if (not ok) { if (auto call = wCall.lock()) { JAMI_WARNING("[call:{}] no devices found", call->getCallId()); // Note: if a p2p connection exists, the call will be at least in CONNECTING if (call->getConnectionState() == Call::ConnectionState::TRYING) call->onFailure(static_cast<int>(std::errc::no_such_device_or_address)); } } }); } void JamiAccount::onConnectedOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& to_id, dhtnet::IpAddr target) { if (!call) return; JAMI_LOG("[call:{}] outgoing call connected to {}", call->getCallId(), to_id); const auto localAddress = dhtnet::ip_utils::getInterfaceAddr(getLocalInterface(), target.getFamily()); dhtnet::IpAddr addrSdp = getPublishedSameasLocal() ? localAddress : connectionManager_->getPublishedIpAddress(target.getFamily()); // fallback on local address if (not addrSdp) addrSdp = localAddress; // Initialize the session using ULAW as default codec in case of early media // The session should be ready to receive media once the first INVITE is sent, before // the session initialization is completed if (!getSystemCodecContainer()->searchCodecByName("PCMA", jami::MEDIA_AUDIO)) JAMI_WARNING("[call:{}] Unable to instantiate codec for early media", call->getCallId()); // Building the local SDP offer auto& sdp = call->getSDP(); sdp.setPublishedIP(addrSdp); auto mediaAttrList = call->getMediaAttributeList(); if (mediaAttrList.empty()) { JAMI_ERROR("[call:{}] no media. Abort!", call->getCallId()); return; } if (not sdp.createOffer(mediaAttrList)) { JAMI_ERROR("[call:{}] Unable to send outgoing INVITE request for new call", call->getCallId()); return; } // Note: pj_ice_strans_create can call onComplete in the same thread // This means that iceMutex_ in IceTransport can be locked when onInitDone is called // So, we need to run the call creation in the main thread // Also, we do not directly call SIPStartCall before receiving onInitDone, because // there is an inside waitForInitialization that can block the thread. // Note: avoid runMainThread as SIPStartCall use transportMutex dht::ThreadPool::io().run([w = weak(), call = std::move(call), target] { auto account = w.lock(); if (not account) return; if (not account->SIPStartCall(*call, target)) { JAMI_ERROR("[call:{}] Unable to send outgoing INVITE request for new call", call->getCallId()); } }); } bool JamiAccount::SIPStartCall(SIPCall& call, const dhtnet::IpAddr& target) { JAMI_LOG("[call:{}] Start SIP call", call.getCallId()); if (call.isIceEnabled()) call.addLocalIceAttributes(); std::string toUri(getToUri(call.getPeerNumber() + "@" + target.toString(true))); // expecting a fully well formed sip uri pj_str_t pjTo = sip_utils::CONST_PJ_STR(toUri); // Create the from header std::string from(getFromUri()); pj_str_t pjFrom = sip_utils::CONST_PJ_STR(from); std::string targetStr = getToUri(target.toString(true)); pj_str_t pjTarget = sip_utils::CONST_PJ_STR(targetStr); auto contact = call.getContactHeader(); auto pjContact = sip_utils::CONST_PJ_STR(contact); JAMI_LOG("[call:{}] contact header: {} / {} -> {} / {}", call.getCallId(), contact, from, toUri, targetStr); auto local_sdp = call.getSDP().getLocalSdpSession(); pjsip_dialog* dialog {nullptr}; pjsip_inv_session* inv {nullptr}; if (!CreateClientDialogAndInvite(&pjFrom, &pjContact, &pjTo, &pjTarget, local_sdp, &dialog, &inv)) return false; inv->mod_data[link_.getModId()] = &call; call.setInviteSession(inv); pjsip_tx_data* tdata; if (pjsip_inv_invite(call.inviteSession_.get(), &tdata) != PJ_SUCCESS) { JAMI_ERROR("[call:{}] Unable to initialize invite", call.getCallId()); return false; } pjsip_tpselector tp_sel; tp_sel.type = PJSIP_TPSELECTOR_TRANSPORT; if (!call.getTransport()) { JAMI_ERROR("[call:{}] Unable to get transport", call.getCallId()); return false; } tp_sel.u.transport = call.getTransport()->get(); if (pjsip_dlg_set_transport(dialog, &tp_sel) != PJ_SUCCESS) { JAMI_ERROR("[call:{}] Unable to associate transport for invite session dialog", call.getCallId()); return false; } JAMI_LOG("[call:{}] Sending SIP invite", call.getCallId()); // Add user-agent header sip_utils::addUserAgentHeader(getUserAgentName(), tdata); if (pjsip_inv_send_msg(call.inviteSession_.get(), tdata) != PJ_SUCCESS) { JAMI_ERROR("[call:{}] Unable to send invite message", call.getCallId()); return false; } call.setState(Call::CallState::ACTIVE, Call::ConnectionState::PROGRESSING); return true; } void JamiAccount::saveConfig() const { try { YAML::Emitter accountOut; config().serialize(accountOut); auto accountConfig = config().path / "config.yml"; std::lock_guard lock(dhtnet::fileutils::getFileLock(accountConfig)); std::ofstream fout(accountConfig); fout.write(accountOut.c_str(), accountOut.size()); JAMI_LOG("Saved account config to {}", accountConfig); } catch (const std::exception& e) { JAMI_ERROR("Error saving account config: {}", e.what()); } } void JamiAccount::loadConfig() { SIPAccountBase::loadConfig(); registeredName_ = config().registeredName; if (accountManager_) accountManager_->setAccountDeviceName(config().deviceName); if (connectionManager_) { if (auto c = connectionManager_->getConfig()) { // Update connectionManager's config c->upnpEnabled = config().upnpEnabled; c->turnEnabled = config().turnEnabled; c->turnServer = config().turnServer; c->turnServerUserName = config().turnServerUserName; c->turnServerPwd = config().turnServerPwd; c->turnServerRealm = config().turnServerRealm; } } if (config().proxyEnabled) { try { auto str = fileutils::loadCacheTextFile(cachePath_ / "dhtproxy", std::chrono::hours(24 * 7)); std::string err; Json::Value root; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (reader->parse(str.data(), str.data() + str.size(), &root, &err)) { proxyServerCached_ = root[getProxyConfigKey()].asString(); } } catch (const std::exception& e) { JAMI_LOG("[Account {}] Unable to load proxy URL from cache: {}", getAccountID(), e.what()); proxyServerCached_.clear(); } } else { proxyServerCached_.clear(); std::error_code ec; std::filesystem::remove(cachePath_ / "dhtproxy", ec); } auto credentials = consumeConfigCredentials(); loadAccount(credentials.archive_password_scheme, credentials.archive_password, credentials.archive_pin, credentials.archive_path); } bool JamiAccount::changeArchivePassword(const std::string& password_old, const std::string& password_new) { try { if (!accountManager_->changePassword(password_old, password_new)) { JAMI_ERROR("[Account {}] Unable to change archive password", getAccountID()); return false; } editConfig([&](JamiAccountConfig& config) { config.archiveHasPassword = not password_new.empty(); }); } catch (const std::exception& ex) { JAMI_ERROR("[Account {}] Unable to change archive password: {}", getAccountID(), ex.what()); if (password_old.empty()) { editConfig([&](JamiAccountConfig& config) { config.archiveHasPassword = true; }); emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails()); } return false; } if (password_old != password_new) emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails()); return true; } bool JamiAccount::isPasswordValid(const std::string& password) { return accountManager_ and accountManager_->isPasswordValid(password); } std::vector<uint8_t> JamiAccount::getPasswordKey(const std::string& password) { return accountManager_ ? accountManager_->getPasswordKey(password) : std::vector<uint8_t>(); } void JamiAccount::addDevice(const std::string& password) { if (not accountManager_) { emitSignal<libjami::ConfigurationSignal::ExportOnRingEnded>(getAccountID(), 2, ""); return; } accountManager_ ->addDevice(password, [this](AccountManager::AddDeviceResult result, std::string pin) { switch (result) { case AccountManager::AddDeviceResult::SUCCESS_SHOW_PIN: emitSignal<libjami::ConfigurationSignal::ExportOnRingEnded>(getAccountID(), 0, pin); break; case AccountManager::AddDeviceResult::ERROR_CREDENTIALS: emitSignal<libjami::ConfigurationSignal::ExportOnRingEnded>(getAccountID(), 1, ""); break; case AccountManager::AddDeviceResult::ERROR_NETWORK: emitSignal<libjami::ConfigurationSignal::ExportOnRingEnded>(getAccountID(), 2, ""); break; } }); } bool JamiAccount::exportArchive(const std::string& destinationPath, std::string_view scheme, const std::string& password) { if (auto manager = dynamic_cast<ArchiveAccountManager*>(accountManager_.get())) { return manager->exportArchive(destinationPath, scheme, password); } return false; } bool JamiAccount::setValidity(std::string_view scheme, const std::string& pwd, const dht::InfoHash& id, int64_t validity) { if (auto manager = dynamic_cast<ArchiveAccountManager*>(accountManager_.get())) { if (manager->setValidity(scheme, pwd, id_, id, validity)) { saveIdentity(id_, idPath_, DEVICE_ID_PATH); return true; } } return false; } void JamiAccount::forceReloadAccount() { editConfig([&](JamiAccountConfig& conf) { conf.receipt.clear(); conf.receiptSignature.clear(); }); loadAccount(); } void JamiAccount::unlinkConversations(const std::set<std::string>& removed) { std::lock_guard lock(configurationMutex_); if (auto info = accountManager_->getInfo()) { auto contacts = info->contacts->getContacts(); for (auto& [id, c] : contacts) { if (removed.find(c.conversationId) != removed.end()) { info->contacts->updateConversation(id, ""); JAMI_WARNING( "[Account {}] Detected removed conversation ({}) in contact details for {}", getAccountID(), c.conversationId, id.toString()); } } } } bool JamiAccount::isValidAccountDevice(const dht::crypto::Certificate& cert) const { if (accountManager_) { if (auto info = accountManager_->getInfo()) { if (info->contacts) return info->contacts->isValidAccountDevice(cert).isValid(); } } return false; } bool JamiAccount::revokeDevice(const std::string& device, std::string_view scheme, const std::string& password) { if (not accountManager_) return false; return accountManager_->revokeDevice( device, scheme, password, [this, device](AccountManager::RevokeDeviceResult result) { emitSignal<libjami::ConfigurationSignal::DeviceRevocationEnded>(getAccountID(), device, static_cast<int>( result)); }); return true; } std::pair<std::string, std::string> JamiAccount::saveIdentity(const dht::crypto::Identity id, const std::filesystem::path& path, const std::string& name) { auto names = std::make_pair(name + ".key", name + ".crt"); if (id.first) fileutils::saveFile(path / names.first, id.first->serialize(), 0600); if (id.second) fileutils::saveFile(path / names.second, id.second->getPacked(), 0600); return names; } // must be called while configurationMutex_ is locked void JamiAccount::loadAccount(const std::string& archive_password_scheme, const std::string& archive_password, const std::string& archive_pin, const std::string& archive_path) { if (registrationState_ == RegistrationState::INITIALIZING) return; JAMI_DEBUG("[Account {:s}] loading account", getAccountID()); AccountManager::OnChangeCallback callbacks { [this](const std::string& uri, bool confirmed) { if (!id_.first) return; if (jami::Manager::instance().syncOnRegister) { dht::ThreadPool::io().run([w = weak(), uri, confirmed] { if (auto shared = w.lock()) { if (auto cm = shared->convModule(true)) { auto activeConv = cm->getOneToOneConversation(uri); if (!activeConv.empty()) cm->bootstrap(activeConv); } emitSignal<libjami::ConfigurationSignal::ContactAdded>(shared->getAccountID(), uri, confirmed); } }); } }, [this](const std::string& uri, bool banned) { if (!id_.first) return; dht::ThreadPool::io().run([w = weak(), uri, banned] { if (auto shared = w.lock()) { // Erase linked conversation's requests if (auto convModule = shared->convModule(true)) convModule->removeContact(uri, banned); // Remove current connections with contact // Note: if contact is ourself, we don't close the connection // because it's used for syncing other conversations. if (shared->connectionManager_ && uri != shared->getUsername()) { shared->connectionManager_->closeConnectionsWith(uri); } // Update client. emitSignal<libjami::ConfigurationSignal::ContactRemoved>(shared->getAccountID(), uri, banned); } }); }, [this](const std::string& uri, const std::string& conversationId, const std::vector<uint8_t>& payload, time_t received) { if (!id_.first) return; dht::ThreadPool::io().run([w = weak(), uri, conversationId, payload, received] { if (auto shared = w.lock()) { shared->clearProfileCache(uri); if (conversationId.empty()) { // Old path emitSignal<libjami::ConfigurationSignal::IncomingTrustRequest>( shared->getAccountID(), conversationId, uri, payload, received); return; } // Here account can be initializing if (auto cm = shared->convModule(true)) { auto activeConv = cm->getOneToOneConversation(uri); if (activeConv != conversationId) cm->onTrustRequest(uri, conversationId, payload, received); } } }); }, [this](const std::map<DeviceId, KnownDevice>& devices) { std::map<std::string, std::string> ids; for (auto& d : devices) { auto id = d.first.toString(); auto label = d.second.name.empty() ? id.substr(0, 8) : d.second.name; ids.emplace(std::move(id), std::move(label)); } runOnMainThread([id = getAccountID(), devices = std::move(ids)] { emitSignal<libjami::ConfigurationSignal::KnownDevicesChanged>(id, devices); }); }, [this](const std::string& conversationId, const std::string& deviceId) { // Note: Do not retrigger on another thread. This has to be done // at the same time of acceptTrustRequest a synced state between TrustRequest // and convRequests. if (auto cm = convModule(true)) cm->acceptConversationRequest(conversationId, deviceId); }, [this](const std::string& uri, const std::string& convFromReq) { dht::ThreadPool::io().run([w = weak(), convFromReq, uri] { if (auto shared = w.lock()) { auto cm = shared->convModule(true); // Remove cached payload if there is one auto requestPath = shared->cachePath_ / "requests" / uri; dhtnet::fileutils::remove(requestPath); if (!convFromReq.empty()) { auto oldConv = cm->getOneToOneConversation(uri); // If we previously removed the contact, and re-add it, we may // receive a convId different from the request. In that case, // we need to remove the current conversation and clone the old // one (given by convFromReq). // TODO: In the future, we may want to re-commit the messages we // may have send in the request we sent. if (oldConv != convFromReq && cm->updateConvForContact(uri, oldConv, convFromReq)) { cm->initReplay(oldConv, convFromReq); cm->cloneConversationFrom(convFromReq, uri, oldConv); } } } }); }}; const auto& conf = config(); try { auto oldIdentity = id_.first ? id_.first->getPublicKey().getLongId() : DeviceId(); if (conf.managerUri.empty()) { accountManager_ = std::make_shared<ArchiveAccountManager>( getPath(), [this]() { return getAccountDetails(); }, conf.archivePath.empty() ? "archive.gz" : conf.archivePath, conf.nameServer); } else { accountManager_ = std::make_shared<ServerAccountManager>(getPath(), conf.managerUri, conf.nameServer); } auto id = accountManager_->loadIdentity(getAccountID(), conf.tlsCertificateFile, conf.tlsPrivateKeyFile, conf.tlsPassword); if (auto info = accountManager_->useIdentity(getAccountID(), id, conf.receipt, conf.receiptSignature, conf.managerUsername, callbacks)) { // normal loading path id_ = std::move(id); config_->username = info->accountId; JAMI_WARNING("[Account {:s}] loaded account identity", getAccountID()); if (info->identity.first->getPublicKey().getLongId() != oldIdentity) { JAMI_WARNING("[Account {:s}] identity changed", getAccountID()); { std::lock_guard lk(moduleMtx_); convModule_.reset(); } convModule(); // convModule must absolutely be initialized in // both branches of the if statement here in order // for it to exist for subsequent use. } else { convModule()->setAccountManager(accountManager_); } if (not isEnabled()) { setRegistrationState(RegistrationState::UNREGISTERED); } } else if (isEnabled()) { JAMI_WARNING("[Account {}] useIdentity failed!", getAccountID()); if (not conf.managerUri.empty() and archive_password.empty()) { Migration::setState(accountID_, Migration::State::INVALID); setRegistrationState(RegistrationState::ERROR_NEED_MIGRATION); return; } bool migrating = registrationState_ == RegistrationState::ERROR_NEED_MIGRATION; setRegistrationState(RegistrationState::INITIALIZING); auto fDeviceKey = dht::ThreadPool::computation() .getShared<std::shared_ptr<dht::crypto::PrivateKey>>([]() { return std::make_shared<dht::crypto::PrivateKey>( dht::crypto::PrivateKey::generate()); }); std::unique_ptr<AccountManager::AccountCredentials> creds; if (conf.managerUri.empty()) { auto acreds = std::make_unique<ArchiveAccountManager::ArchiveAccountCredentials>(); auto archivePath = fileutils::getFullPath(idPath_, conf.archivePath); bool hasArchive = std::filesystem::is_regular_file(archivePath); if (not archive_path.empty()) { // Importing external archive acreds->scheme = "file"; acreds->uri = archive_path; } else if (not archive_pin.empty()) { // Importing from DHT acreds->scheme = "dht"; acreds->uri = archive_pin; acreds->dhtBootstrap = loadBootstrap(); acreds->dhtPort = dhtPortUsed(); } else if (hasArchive) { // Migrating local account acreds->scheme = "local"; acreds->uri = std::move(archivePath).string(); acreds->updateIdentity = id; migrating = true; } creds = std::move(acreds); } else { auto screds = std::make_unique<ServerAccountManager::ServerAccountCredentials>(); screds->username = conf.managerUsername; creds = std::move(screds); } creds->password = archive_password; bool hasPassword = !archive_password.empty(); if (hasPassword && archive_password_scheme.empty()) creds->password_scheme = fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD; else creds->password_scheme = archive_password_scheme; accountManager_->initAuthentication( getAccountID(), fDeviceKey, ip_utils::getDeviceName(), std::move(creds), [w = weak(), this, migrating, hasPassword](const AccountInfo& info, const std::map<std::string, std::string>& config, std::string&& receipt, std::vector<uint8_t>&& receipt_signature) { auto sthis = w.lock(); if (not sthis) return; JAMI_LOG("[Account {}] Auth success!", getAccountID()); dhtnet::fileutils::check_dir(idPath_, 0700); auto id = info.identity; editConfig([&](JamiAccountConfig& conf) { std::tie(conf.tlsPrivateKeyFile, conf.tlsCertificateFile) = saveIdentity(id, idPath_, DEVICE_ID_PATH); conf.tlsPassword = {}; conf.archiveHasPassword = hasPassword; if (not conf.managerUri.empty()) { conf.registeredName = conf.managerUsername; registeredName_ = conf.managerUsername; } conf.username = info.accountId; conf.deviceName = accountManager_->getAccountDeviceName(); auto nameServerIt = config.find( libjami::Account::ConfProperties::RingNS::URI); if (nameServerIt != config.end() && !nameServerIt->second.empty()) { conf.nameServer = nameServerIt->second; } auto displayNameIt = config.find( libjami::Account::ConfProperties::DISPLAYNAME); if (displayNameIt != config.end() && !displayNameIt->second.empty()) { conf.displayName = displayNameIt->second; } conf.receipt = std::move(receipt); conf.receiptSignature = std::move(receipt_signature); conf.fromMap(config); }); id_ = std::move(id); { std::lock_guard lk(moduleMtx_); convModule_.reset(); } if (migrating) { Migration::setState(getAccountID(), Migration::State::SUCCESS); } if (not info.photo.empty() or not config_->displayName.empty()) emitSignal<libjami::ConfigurationSignal::AccountProfileReceived>( getAccountID(), config_->displayName, info.photo); setRegistrationState(RegistrationState::UNREGISTERED); doRegister(); }, [w = weak(), id, accountId = getAccountID(), migrating](AccountManager::AuthError error, const std::string& message) { JAMI_WARNING("[Account {}] Auth error: {} {}", accountId, (int) error, message); if ((id.first || migrating) && error == AccountManager::AuthError::INVALID_ARGUMENTS) { // In cast of a migration or manager connexion failure stop the migration // and block the account Migration::setState(accountId, Migration::State::INVALID); if (auto acc = w.lock()) acc->setRegistrationState(RegistrationState::ERROR_NEED_MIGRATION); } else { // In case of a DHT or backup import failure, just remove the account if (auto acc = w.lock()) acc->setRegistrationState(RegistrationState::ERROR_GENERIC); runOnMainThread([accountId = std::move(accountId)] { Manager::instance().removeAccount(accountId, true); }); } }, callbacks); } } catch (const std::exception& e) { JAMI_WARNING("[Account {}] error loading account: {}", getAccountID(), e.what()); accountManager_.reset(); setRegistrationState(RegistrationState::ERROR_GENERIC); } } std::map<std::string, std::string> JamiAccount::getVolatileAccountDetails() const { auto a = SIPAccountBase::getVolatileAccountDetails(); a.emplace(libjami::Account::VolatileProperties::InstantMessaging::OFF_CALL, TRUE_STR); #if HAVE_RINGNS auto registeredName = getRegisteredName(); if (not registeredName.empty()) a.emplace(libjami::Account::VolatileProperties::REGISTERED_NAME, registeredName); #endif a.emplace(libjami::Account::ConfProperties::PROXY_SERVER, proxyServerCached_); a.emplace(libjami::Account::VolatileProperties::DHT_BOUND_PORT, std::to_string(dhtBoundPort_)); a.emplace(libjami::Account::VolatileProperties::DEVICE_ANNOUNCED, deviceAnnounced_ ? TRUE_STR : FALSE_STR); if (accountManager_) { if (auto info = accountManager_->getInfo()) { a.emplace(libjami::Account::ConfProperties::DEVICE_ID, info->deviceId); } } return a; } #if HAVE_RINGNS void JamiAccount::lookupName(const std::string& name) { std::lock_guard lock(configurationMutex_); if (accountManager_) accountManager_->lookupUri(name, config().nameServer, [acc = getAccountID(), name](const std::string& result, NameDirectory::Response response) { emitSignal<libjami::ConfigurationSignal::RegisteredNameFound>( acc, (int) response, result, name); }); } void JamiAccount::lookupAddress(const std::string& addr) { std::lock_guard lock(configurationMutex_); auto acc = getAccountID(); if (accountManager_) accountManager_->lookupAddress( addr, [acc, addr](const std::string& result, NameDirectory::Response response) { emitSignal<libjami::ConfigurationSignal::RegisteredNameFound>(acc, (int) response, addr, result); }); } void JamiAccount::registerName(const std::string& name, const std::string& scheme, const std::string& password) { std::lock_guard lock(configurationMutex_); if (accountManager_) accountManager_->registerName( name, scheme, password, [acc = getAccountID(), name, w = weak()](NameDirectory::RegistrationResponse response, const std::string& regName) { auto res = (int) std::min(response, NameDirectory::RegistrationResponse::error); if (response == NameDirectory::RegistrationResponse::success) { if (auto this_ = w.lock()) { if (this_->setRegisteredName(regName)) { this_->editConfig([&](JamiAccountConfig& config) { config.registeredName = regName; }); emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>( this_->accountID_, this_->getVolatileAccountDetails()); } } } emitSignal<libjami::ConfigurationSignal::NameRegistrationEnded>(acc, res, name); }); } #endif bool JamiAccount::searchUser(const std::string& query) { if (accountManager_) return accountManager_->searchUser( query, [acc = getAccountID(), query](const jami::NameDirectory::SearchResult& result, jami::NameDirectory::Response response) { jami::emitSignal<libjami::ConfigurationSignal::UserSearchEnded>(acc, (int) response, query, result); }); return false; } void JamiAccount::forEachPendingCall(const DeviceId& deviceId, const std::function<void(const std::shared_ptr<SIPCall>&)>& cb) { std::vector<std::shared_ptr<SIPCall>> pc; { std::lock_guard lk(pendingCallsMutex_); pc = std::move(pendingCalls_[deviceId]); } for (const auto& pendingCall : pc) { cb(pendingCall); } } void JamiAccount::registerAsyncOps() { auto onLoad = [this, loaded = std::make_shared<std::atomic_uint>()] { if (++(*loaded) == 2u) { runOnMainThread([w = weak()] { if (auto s = w.lock()) { std::lock_guard lock(s->configurationMutex_); s->doRegister_(); } }); } }; loadCachedProxyServer([onLoad](const std::string&) { onLoad(); }); if (upnpCtrl_) { JAMI_LOG("[Account {:s}] UPnP: attempting to map ports", getAccountID()); // Release current mapping if any. if (dhtUpnpMapping_.isValid()) { upnpCtrl_->releaseMapping(dhtUpnpMapping_); } dhtUpnpMapping_.enableAutoUpdate(true); // Set the notify callback. dhtUpnpMapping_.setNotifyCallback([w = weak(), onLoad, update = std::make_shared<bool>(false)]( dhtnet::upnp::Mapping::sharedPtr_t mapRes) { if (auto accPtr = w.lock()) { auto& dhtMap = accPtr->dhtUpnpMapping_; const auto& accId = accPtr->getAccountID(); JAMI_LOG("[Account {:s}] DHT UPNP mapping changed to {:s}", accId, mapRes->toString(true)); if (*update) { // Check if we need to update the mapping and the registration. if (dhtMap.getMapKey() != mapRes->getMapKey() or dhtMap.getState() != mapRes->getState()) { // The connectivity must be restarted, if either: // - the state changed to "OPEN", // - the state changed to "FAILED" and the mapping was in use. if (mapRes->getState() == dhtnet::upnp::MappingState::OPEN or (mapRes->getState() == dhtnet::upnp::MappingState::FAILED and dhtMap.getState() == dhtnet::upnp::MappingState::OPEN)) { // Update the mapping and restart the registration. dhtMap.updateFrom(mapRes); JAMI_WARNING( "[Account {:s}] Allocated port changed to {}. Restarting the " "registration", accId, accPtr->dhtPortUsed()); accPtr->dht_->connectivityChanged(); } else { // Only update the mapping. dhtMap.updateFrom(mapRes); } } } else { *update = true; // Set connection info and load the account. if (mapRes->getState() == dhtnet::upnp::MappingState::OPEN) { dhtMap.updateFrom(mapRes); JAMI_LOG( "[Account {:s}] Mapping {:s} successfully allocated: starting the DHT", accId, dhtMap.toString()); } else { JAMI_WARNING("[Account {:s}] Mapping request is in {:s} state: starting " "the DHT anyway", accId, mapRes->getStateStr()); } // Load the account and start the DHT. onLoad(); } } }); // Request the mapping. auto map = upnpCtrl_->reserveMapping(dhtUpnpMapping_); // The returned mapping is invalid. Load the account now since // we may never receive the callback. if (not map) { onLoad(); } } else { // No UPNP. Load the account and start the DHT. The local DHT // might not be reachable for peers if we are behind a NAT. onLoad(); } } void JamiAccount::doRegister() { std::lock_guard lock(configurationMutex_); if (not isUsable()) { JAMI_WARNING("[Account {:s}] Account must be enabled and active to register, ignoring", getAccountID()); return; } JAMI_LOG("[Account {:s}] Starting account..", getAccountID()); // invalid state transitions: // INITIALIZING: generating/loading certificates, unable to register // NEED_MIGRATION: old account detected, user needs to migrate if (registrationState_ == RegistrationState::INITIALIZING || registrationState_ == RegistrationState::ERROR_NEED_MIGRATION) return; convModule(); // Init conv module before passing in trying setRegistrationState(RegistrationState::TRYING); /* if UPnP is enabled, then wait for IGD to complete registration */ if (upnpCtrl_ or proxyServerCached_.empty()) { registerAsyncOps(); } else { doRegister_(); } } std::vector<std::string> JamiAccount::loadBootstrap() const { std::vector<std::string> bootstrap; std::string_view stream(config().hostname), node_addr; while (jami::getline(stream, node_addr, ';')) bootstrap.emplace_back(node_addr); for (const auto& b : bootstrap) JAMI_DBG("[Account %s] Bootstrap node: %s", getAccountID().c_str(), b.c_str()); return bootstrap; } void JamiAccount::trackBuddyPresence(const std::string& buddy_id, bool track) { std::string buddyUri; try { buddyUri = parseJamiUri(buddy_id); } catch (...) { JAMI_ERR("[Account %s] Failed to track presence: invalid URI %s", getAccountID().c_str(), buddy_id.c_str()); return; } JAMI_DBG("[Account %s] %s presence for %s", getAccountID().c_str(), track ? "Track" : "Untrack", buddy_id.c_str()); auto h = dht::InfoHash(buddyUri); std::unique_lock lock(buddyInfoMtx); if (track) { auto buddy = trackedBuddies_.emplace(h, BuddyInfo {h}); if (buddy.second) { trackPresence(buddy.first->first, buddy.first->second); } auto it = presenceState_.find(buddyUri); if (it != presenceState_.end() && it->second != PresenceState::DISCONNECTED) { lock.unlock(); emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(), buddyUri, static_cast<int>(it->second), ""); } } else { auto buddy = trackedBuddies_.find(h); if (buddy != trackedBuddies_.end()) { if (auto dht = dht_) if (dht->isRunning()) dht->cancelListen(h, std::move(buddy->second.listenToken)); trackedBuddies_.erase(buddy); } } } void JamiAccount::trackPresence(const dht::InfoHash& h, BuddyInfo& buddy) { auto dht = dht_; if (not dht or not dht->isRunning()) { return; } buddy.listenToken = dht->listen<DeviceAnnouncement>(h, [this, h](DeviceAnnouncement&& dev, bool expired) { bool wasConnected, isConnected; { std::lock_guard lock(buddyInfoMtx); auto buddy = trackedBuddies_.find(h); if (buddy == trackedBuddies_.end()) return true; wasConnected = buddy->second.devices_cnt > 0; if (expired) --buddy->second.devices_cnt; else ++buddy->second.devices_cnt; isConnected = buddy->second.devices_cnt > 0; } // NOTE: the rest can use configurationMtx_, that can be locked during unregister so // do not retrigger on dht runOnMainThread([w = weak(), h, dev, expired, isConnected, wasConnected]() { auto sthis = w.lock(); if (!sthis) return; if (not expired) { // Retry messages every time a new device announce its presence sthis->messageEngine_.onPeerOnline(h.toString()); } if (isConnected and not wasConnected) { sthis->onTrackedBuddyOnline(h); } else if (not isConnected and wasConnected) { sthis->onTrackedBuddyOffline(h); } }); return true; }); } std::map<std::string, bool> JamiAccount::getTrackedBuddyPresence() const { std::lock_guard lock(buddyInfoMtx); std::map<std::string, bool> presence_info; for (const auto& buddy_info_p : trackedBuddies_) presence_info.emplace(buddy_info_p.first.toString(), buddy_info_p.second.devices_cnt > 0); return presence_info; } void JamiAccount::onTrackedBuddyOnline(const dht::InfoHash& contactId) { std::string id(contactId.toString()); JAMI_DEBUG("Buddy {} online", id); auto& state = presenceState_[id]; if (state < PresenceState::AVAILABLE) { state = PresenceState::AVAILABLE; emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(), id, static_cast<int>( PresenceState::AVAILABLE), ""); } auto details = getContactDetails(id); auto it = details.find("confirmed"); if (it == details.end() or it->second == "false") { auto convId = convModule()->getOneToOneConversation(id); if (convId.empty()) return; // In this case, the TrustRequest was sent but never confirmed (cause the contact was // offline maybe) To avoid the contact to never receive the conv request, retry there std::lock_guard lock(configurationMutex_); if (accountManager_) { // Retrieve cached payload for trust request. auto requestPath = cachePath_ / "requests" / id; std::vector<uint8_t> payload; try { payload = fileutils::loadFile(requestPath); } catch (...) { } if (payload.size() >= 64000) { JAMI_WARN() << "Trust request is too big, reset payload"; payload.clear(); } accountManager_->sendTrustRequest(id, convId, payload); } } } void JamiAccount::onTrackedBuddyOffline(const dht::InfoHash& contactId) { auto id = contactId.toString(); JAMI_DEBUG("Buddy {} offline", id); auto& state = presenceState_[id]; if (state > PresenceState::DISCONNECTED) { if (state == PresenceState::CONNECTED) { JAMI_WARNING("Buddy {} is not present on the DHT, but p2p connected", id); } state = PresenceState::DISCONNECTED; emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(), id, static_cast<int>( PresenceState::DISCONNECTED), ""); } } void JamiAccount::doRegister_() { if (registrationState_ != RegistrationState::TRYING) { JAMI_ERROR("[Account {}] already registered", getAccountID()); return; } JAMI_DEBUG("[Account {}] Starting account...", getAccountID()); const auto& conf = config(); try { if (not accountManager_ or not accountManager_->getInfo()) throw std::runtime_error("No identity configured for this account."); if (dht_->isRunning()) { JAMI_ERROR("[Account {}] DHT already running (stopping it first).", getAccountID()); dht_->join(); } convModule()->clearPendingFetch(); #if HAVE_RINGNS // Look for registered name accountManager_->lookupAddress( accountManager_->getInfo()->accountId, [w = weak()](const std::string& result, const NameDirectory::Response& response) { if (auto this_ = w.lock()) { if (response == NameDirectory::Response::found or response == NameDirectory::Response::notFound) { const auto& nameResult = response == NameDirectory::Response::found ? result : ""; if (this_->setRegisteredName(nameResult)) { this_->editConfig([&](JamiAccountConfig& config) { config.registeredName = nameResult; }); emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>( this_->accountID_, this_->getVolatileAccountDetails()); } } } }); #endif dht::DhtRunner::Config config {}; config.dht_config.node_config.network = 0; config.dht_config.node_config.maintain_storage = false; config.dht_config.node_config.persist_path = (cachePath_ / "dhtstate").string(); config.dht_config.id = id_; config.dht_config.cert_cache_all = true; config.push_node_id = getAccountID(); config.push_token = conf.deviceKey; config.push_topic = conf.notificationTopic; config.push_platform = conf.platform; config.proxy_user_agent = jami::userAgent(); config.threaded = true; config.peer_discovery = conf.dhtPeerDiscovery; config.peer_publish = conf.dhtPeerDiscovery; if (conf.proxyEnabled) config.proxy_server = proxyServerCached_; if (not config.proxy_server.empty()) { JAMI_LOG("[Account {}] using proxy server {}", getAccountID(), config.proxy_server); if (not config.push_token.empty()) { JAMI_LOG( "[Account {}] using push notifications with platform: {}, topic: {}, token: {}", getAccountID(), config.push_platform, config.push_topic, config.push_token); } } // check if dht peer service is enabled if (conf.accountPeerDiscovery or conf.accountPublish) { peerDiscovery_ = std::make_shared<dht::PeerDiscovery>(); if (conf.accountPeerDiscovery) { JAMI_LOG("[Account {}] starting Jami account discovery...", getAccountID()); startAccountDiscovery(); } if (conf.accountPublish) startAccountPublish(); } dht::DhtRunner::Context context {}; context.peerDiscovery = peerDiscovery_; context.rng = std::make_unique<std::mt19937_64>(dht::crypto::getDerivedRandomEngine(rand)); auto dht_log_level = Manager::instance().dhtLogLevel.load(); if (dht_log_level > 0) { context.logger = Logger::dhtLogger(); } context.certificateStore = [&](const dht::InfoHash& pk_id) { std::vector<std::shared_ptr<dht::crypto::Certificate>> ret; if (auto cert = certStore().getCertificate(pk_id.toString())) ret.emplace_back(std::move(cert)); JAMI_LOG("Query for local certificate store: {}: {} found.", pk_id.toString(), ret.size()); return ret; }; context.statusChangedCallback = [this](dht::NodeStatus s4, dht::NodeStatus s6) { JAMI_DBG("[Account %s] Dht status: IPv4 %s; IPv6 %s", getAccountID().c_str(), dhtStatusStr(s4), dhtStatusStr(s6)); RegistrationState state; auto newStatus = std::max(s4, s6); switch (newStatus) { case dht::NodeStatus::Connecting: state = RegistrationState::TRYING; break; case dht::NodeStatus::Connected: state = RegistrationState::REGISTERED; break; case dht::NodeStatus::Disconnected: state = RegistrationState::UNREGISTERED; break; default: state = RegistrationState::ERROR_GENERIC; break; } setRegistrationState(state); }; context.identityAnnouncedCb = [this](bool ok) { if (!ok) return; accountManager_->startSync( [this](const std::shared_ptr<dht::crypto::Certificate>& crt) { if (jami::Manager::instance().syncOnRegister) { if (!crt) return; auto deviceId = crt->getLongId().toString(); if (accountManager_->getInfo()->deviceId == deviceId) return; std::unique_lock lk(connManagerMtx_); initConnectionManager(); lk.unlock(); requestSIPConnection( getUsername(), crt->getLongId(), "sync"); // For git notifications, will use the same socket as sync } }, [this] { if (jami::Manager::instance().syncOnRegister) { deviceAnnounced_ = true; // Bootstrap at the end to avoid to be long to load. dht::ThreadPool::io().run([w = weak()] { if (auto shared = w.lock()) shared->convModule()->bootstrap(); }); emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>( accountID_, getVolatileAccountDetails()); } }, publishPresence_); }; dht_->run(dhtPortUsed(), config, std::move(context)); for (const auto& bootstrap : loadBootstrap()) dht_->bootstrap(bootstrap); dhtBoundPort_ = dht_->getBoundPort(); accountManager_->setDht(dht_); std::unique_lock lkCM(connManagerMtx_); initConnectionManager(); connectionManager_->onDhtConnected(*accountManager_->getInfo()->devicePk); connectionManager_->onICERequest([this](const DeviceId& deviceId) { std::promise<bool> accept; std::future<bool> fut = accept.get_future(); accountManager_->findCertificate( deviceId, [this, &accept](const std::shared_ptr<dht::crypto::Certificate>& cert) { dht::InfoHash peer_account_id; auto res = accountManager_->onPeerCertificate(cert, this->config().dhtPublicInCalls, peer_account_id); JAMI_LOG("{} ICE request from {}", res ? "Accepting" : "Discarding", peer_account_id); accept.set_value(res); }); fut.wait(); auto result = fut.get(); return result; }); connectionManager_->onChannelRequest( [this](const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& name) { JAMI_WARNING("[Account {}] New channel asked with name {} from {}", getAccountID(), name, cert->issuer->getId()); if (this->config().turnEnabled && turnCache_) { auto addr = turnCache_->getResolvedTurn(); if (addr == std::nullopt) { // If TURN is enabled, but no TURN cached, there can be a temporary // resolution error to solve. Sometimes, a connectivity change is not // enough, so even if this case is really rare, it should be easy to avoid. turnCache_->refresh(); } } auto uri = Uri(name); std::lock_guard lk(connManagerMtx_); auto itHandler = channelHandlers_.find(uri.scheme()); if (itHandler != channelHandlers_.end() && itHandler->second) return itHandler->second->onRequest(cert, name); return name == "sip"; }); connectionManager_->onConnectionReady([this](const DeviceId& deviceId, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) { if (channel) { auto cert = channel->peerCertificate(); if (!cert || !cert->issuer) return; auto peerId = cert->issuer->getId().toString(); // A connection request can be sent just before member is banned and this must be ignored. if (accountManager()->getCertificateStatus(peerId) == dhtnet::tls::TrustStore::PermissionStatus::BANNED) { channel->shutdown(); return; } if (name == "sip") { cacheSIPConnection(std::move(channel), peerId, deviceId); } else if (name.find("git://") == 0) { auto sep = name.find_last_of('/'); auto conversationId = name.substr(sep + 1); auto remoteDevice = name.substr(6, sep - 6); if (channel->isInitiator()) { // Check if wanted remote it's our side (git://remoteDevice/conversationId) return; } // Check if pull from banned device if (convModule()->isBanned(conversationId, remoteDevice)) { JAMI_WARNING( "[Account {:s}] Git server requested for conversation {:s}, but the " "device is " "unauthorized ({:s}) ", getAccountID(), conversationId, remoteDevice); channel->shutdown(); return; } auto sock = convModule()->gitSocket(deviceId.toString(), conversationId); if (sock == channel) { // The onConnectionReady is already used as client (for retrieving messages) // So it's not the server socket return; } JAMI_WARNING( "[Account {:s}] Git server requested for conversation {:s}, device {:s}, " "channel {}", accountID_, conversationId, deviceId.toString(), channel->channel()); auto gs = std::make_unique<GitServer>(accountID_, conversationId, channel); syncCnt_.fetch_add(1); gs->setOnFetched( [w = weak(), conversationId, deviceId](const std::string& commit) { if (auto shared = w.lock()) { shared->convModule()->setFetched(conversationId, deviceId.toString(), commit); shared->syncCnt_.fetch_sub(1); if (shared->syncCnt_.load() == 0) { emitSignal<libjami::ConversationSignal::ConversationCloned>( shared->getAccountID().c_str()); } } }); const dht::Value::Id serverId = ValueIdDist()(rand); { std::lock_guard lk(gitServersMtx_); gitServers_[serverId] = std::move(gs); } channel->onShutdown([w = weak(), serverId]() { // Run on main thread to avoid to be in mxSock's eventLoop runOnMainThread([serverId, w]() { auto shared = w.lock(); if (!shared) return; std::lock_guard lk(shared->gitServersMtx_); shared->gitServers_.erase(serverId); }); }); } else { // TODO move git:// std::lock_guard lk(connManagerMtx_); auto uri = Uri(name); auto itHandler = channelHandlers_.find(uri.scheme()); if (itHandler != channelHandlers_.end() && itHandler->second) itHandler->second->onReady(cert, name, std::move(channel)); } } }); lkCM.unlock(); if (!conf.managerUri.empty() && accountManager_) { dynamic_cast<ServerAccountManager*>(accountManager_.get())->onNeedsMigration([this]() { editConfig([&](JamiAccountConfig& conf) { conf.receipt.clear(); conf.receiptSignature.clear(); }); Migration::setState(accountID_, Migration::State::INVALID); setRegistrationState(RegistrationState::ERROR_NEED_MIGRATION); }); dynamic_cast<ServerAccountManager*>(accountManager_.get()) ->syncBlueprintConfig([this](const std::map<std::string, std::string>& config) { editConfig([&](JamiAccountConfig& conf) { conf.fromMap(config); }); emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>( getAccountID(), getAccountDetails()); }); } std::lock_guard lock(buddyInfoMtx); for (auto& buddy : trackedBuddies_) { buddy.second.devices_cnt = 0; trackPresence(buddy.first, buddy.second); } } catch (const std::exception& e) { JAMI_ERR("Error registering DHT account: %s", e.what()); setRegistrationState(RegistrationState::ERROR_GENERIC); } } ConversationModule* JamiAccount::convModule(bool noCreation) { if (noCreation) return convModule_.get(); if (!accountManager() || currentDeviceId() == "") { JAMI_ERROR("[Account {}] Calling convModule() with an uninitialized account", getAccountID()); return nullptr; } std::unique_lock<std::recursive_mutex> lock(configurationMutex_); std::lock_guard lk(moduleMtx_); if (!convModule_) { convModule_ = std::make_unique<ConversationModule>( shared(), accountManager_, [this](auto&& syncMsg) { dht::ThreadPool::io().run([w = weak(), syncMsg] { if (auto shared = w.lock()) { auto& config = shared->config(); // For JAMS account, we must update the server if (!config.managerUri.empty()) if (auto am = shared->accountManager()) am->syncDevices(); if (auto sm = shared->syncModule()) sm->syncWithConnected(syncMsg); } }); }, [this](auto&& uri, auto&& device, auto&& msg, auto token = 0) { // No need to retrigger, sendTextMessage will call // messageEngine_.sendMessage, already retriggering on // main thread. auto deviceId = device ? device.toString() : ""; return sendTextMessage(uri, deviceId, msg, token); }, [this](const auto& convId, const auto& deviceId, auto cb, const auto& type) { dht::ThreadPool::io().run([w = weak(), convId, deviceId, cb = std::move(cb), type] { auto shared = w.lock(); if (!shared) return; if (auto socket = shared->convModule()->gitSocket(deviceId, convId)) { if (!cb(socket)) socket->shutdown(); else cb({}); return; } std::unique_lock lkCM(shared->connManagerMtx_); if (!shared->connectionManager_) { lkCM.unlock(); cb({}); return; } shared->connectionManager_->connectDevice( DeviceId(deviceId), fmt::format("git://{}/{}", deviceId, convId), [w, cb = std::move(cb), convId](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId&) { dht::ThreadPool::io().run([w, cb = std::move(cb), socket = std::move(socket), convId] { if (socket) { socket->onShutdown([w, deviceId = socket->deviceId(), convId] { dht::ThreadPool::io().run([w, deviceId, convId] { if (auto shared = w.lock()) shared->convModule() ->removeGitSocket(deviceId.toString(), convId); }); }); if (!cb(socket)) socket->shutdown(); } else cb({}); }); }, false, false, type); }); }, [this](const auto& convId, const auto& deviceId, auto&& cb, const auto& connectionType) { dht::ThreadPool::io().run([w = weak(), convId, deviceId, cb = std::move(cb), connectionType] { auto shared = w.lock(); if (!shared) return; auto cm = shared->convModule(); std::lock_guard lkCM(shared->connManagerMtx_); if (!shared->connectionManager_ || !cm || cm->isBanned(convId, deviceId)) { Manager::instance().ioContext()->post([cb] { cb({}); }); return; } if (!shared->connectionManager_->isConnecting(DeviceId(deviceId), fmt::format("swarm://{}", convId))) { shared->connectionManager_->connectDevice( DeviceId(deviceId), fmt::format("swarm://{}", convId), [w, cb = std::move(cb)](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId& deviceId) { dht::ThreadPool::io().run([w, cb = std::move(cb), socket = std::move(socket), deviceId] { if (socket) { auto shared = w.lock(); if (!shared) return; auto remoteCert = socket->peerCertificate(); auto uri = remoteCert->issuer->getId().toString(); if (shared->accountManager()->getCertificateStatus(uri) == dhtnet::tls::TrustStore::PermissionStatus::BANNED) { cb(nullptr); return; } shared->requestSIPConnection(uri, deviceId, ""); } cb(socket); }); }); } }); }, [this](auto&& convId, auto&& from) { accountManager_ ->findCertificate(dht::InfoHash(from), [this, from, convId]( const std::shared_ptr<dht::crypto::Certificate>& cert) { auto info = accountManager_->getInfo(); if (!cert || !info) return; info->contacts->onTrustRequest(dht::InfoHash(from), cert->getSharedPublicKey(), time(nullptr), false, convId, {}); }); }, autoLoadConversations_); } return convModule_.get(); } SyncModule* JamiAccount::syncModule() { if (!accountManager() || currentDeviceId() == "") { JAMI_ERR() << "Calling syncModule() with an uninitialized account."; return nullptr; } std::lock_guard lk(moduleMtx_); if (!syncModule_) syncModule_ = std::make_unique<SyncModule>(weak()); return syncModule_.get(); } void JamiAccount::onTextMessage(const std::string& id, const std::string& from, const std::string& deviceId, const std::map<std::string, std::string>& payloads) { try { const std::string fromUri {parseJamiUri(from)}; SIPAccountBase::onTextMessage(id, fromUri, deviceId, payloads); } catch (...) { } } void JamiAccount::loadConversation(const std::string& convId) { if (auto cm = convModule(true)) cm->loadSingleConversation(convId); } void JamiAccount::doUnregister(std::function<void(bool)> released_cb) { std::unique_lock<std::recursive_mutex> lock(configurationMutex_); if (registrationState_ >= RegistrationState::ERROR_GENERIC) { lock.unlock(); if (released_cb) released_cb(false); return; } std::mutex mtx; std::condition_variable cv; bool shutdown_complete {false}; if (peerDiscovery_) { peerDiscovery_->stopPublish(PEER_DISCOVERY_JAMI_SERVICE); peerDiscovery_->stopDiscovery(PEER_DISCOVERY_JAMI_SERVICE); } JAMI_WARN("[Account %s] unregistering account %p", getAccountID().c_str(), this); dht_->shutdown( [&] { JAMI_WARN("[Account %s] dht shutdown complete", getAccountID().c_str()); std::lock_guard lock(mtx); shutdown_complete = true; cv.notify_all(); }, true); { std::lock_guard lk(pendingCallsMutex_); pendingCalls_.clear(); } // Stop all current p2p connections if account is disabled // Else, we let the system managing if the co is down or not // NOTE: this is used for changing account's config. if (not isEnabled()) shutdownConnections(); // Release current upnp mapping if any. if (upnpCtrl_ and dhtUpnpMapping_.isValid()) { upnpCtrl_->releaseMapping(dhtUpnpMapping_); } { std::unique_lock lock(mtx); cv.wait(lock, [&] { return shutdown_complete; }); } dht_->join(); setRegistrationState(RegistrationState::UNREGISTERED); lock.unlock(); if (released_cb) released_cb(false); #ifdef ENABLE_PLUGIN jami::Manager::instance().getJamiPluginManager().getChatServicesManager().cleanChatSubjects( getAccountID()); #endif } void JamiAccount::setRegistrationState(RegistrationState state, int detail_code, const std::string& detail_str) { if (registrationState_ != state) { if (state == RegistrationState::REGISTERED) { JAMI_WARNING("[Account {}] connected", getAccountID()); turnCache_->refresh(); if (connectionManager_) connectionManager_->storeActiveIpAddress(); } else if (state == RegistrationState::TRYING) { JAMI_WARNING("[Account {}] connecting…", getAccountID()); } else { deviceAnnounced_ = false; JAMI_WARNING("[Account {}] disconnected", getAccountID()); } } // Update registrationState_ & emit signals Account::setRegistrationState(state, detail_code, detail_str); } void JamiAccount::reloadContacts() { accountManager_->reloadContacts(); } void JamiAccount::connectivityChanged() { JAMI_WARN("connectivityChanged"); if (not isUsable()) { // nothing to do return; } if (auto cm = convModule()) cm->connectivityChanged(); dht_->connectivityChanged(); { std::lock_guard lkCM(connManagerMtx_); if (connectionManager_) { connectionManager_->connectivityChanged(); // reset cache connectionManager_->setPublishedAddress({}); } } } bool JamiAccount::findCertificate( const dht::InfoHash& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb) { if (accountManager_) return accountManager_->findCertificate(h, std::move(cb)); return false; } bool JamiAccount::findCertificate( const dht::PkId& id, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb) { if (accountManager_) return accountManager_->findCertificate(id, std::move(cb)); return false; } bool JamiAccount::findCertificate(const std::string& crt_id) { if (accountManager_) return accountManager_->findCertificate(dht::InfoHash(crt_id)); return false; } bool JamiAccount::setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status) { bool done = accountManager_ ? accountManager_->setCertificateStatus(cert_id, status) : false; if (done) { findCertificate(cert_id); emitSignal<libjami::ConfigurationSignal::CertificateStateChanged>( getAccountID(), cert_id, dhtnet::tls::TrustStore::statusToStr(status)); } return done; } bool JamiAccount::setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert, dhtnet::tls::TrustStore::PermissionStatus status, bool local) { bool done = accountManager_ ? accountManager_->setCertificateStatus(cert, status, local) : false; if (done) { findCertificate(cert->getId().toString()); emitSignal<libjami::ConfigurationSignal::CertificateStateChanged>( getAccountID(), cert->getId().toString(), dhtnet::tls::TrustStore::statusToStr(status)); } return done; } std::vector<std::string> JamiAccount::getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status) { if (accountManager_) return accountManager_->getCertificatesByStatus(status); return {}; } bool JamiAccount::isMessageTreated(dht::Value::Id id) { std::lock_guard lock(messageMutex_); return !treatedMessages_.add(id); } bool JamiAccount::sha3SumVerify() const { return !noSha3sumVerification_; } #ifdef LIBJAMI_TESTABLE void JamiAccount::noSha3sumVerification(bool newValue) { noSha3sumVerification_ = newValue; } #endif std::map<std::string, std::string> JamiAccount::getKnownDevices() const { std::lock_guard lock(configurationMutex_); if (not accountManager_ or not accountManager_->getInfo()) return {}; std::map<std::string, std::string> ids; for (const auto& d : accountManager_->getKnownDevices()) { auto id = d.first.toString(); auto label = d.second.name.empty() ? id.substr(0, 8) : d.second.name; ids.emplace(std::move(id), std::move(label)); } return ids; } void JamiAccount::loadCachedUrl(const std::string& url, const std::filesystem::path& cachePath, const std::chrono::seconds& cacheDuration, std::function<void(const dht::http::Response& response)> cb) { dht::ThreadPool::io().run([cb, url, cachePath, cacheDuration, w = weak()]() { try { std::string data; { std::lock_guard lk(dhtnet::fileutils::getFileLock(cachePath)); data = fileutils::loadCacheTextFile(cachePath, cacheDuration); } dht::http::Response ret; ret.body = std::move(data); ret.status_code = 200; cb(ret); } catch (const std::exception& e) { JAMI_LOG("Failed to load '{}' from '{}': {}", url, cachePath, e.what()); if (auto sthis = w.lock()) { auto req = std::make_shared<dht::http::Request>( *Manager::instance().ioContext(), url, [cb, cachePath, w](const dht::http::Response& response) { if (response.status_code == 200) { try { std::lock_guard lk(dhtnet::fileutils::getFileLock(cachePath)); fileutils::saveFile(cachePath, (const uint8_t*) response.body.data(), response.body.size(), 0600); JAMI_LOG("Cached result to '{}'", cachePath); } catch (const std::exception& ex) { JAMI_WARNING("Failed to save result to '{}': {}", cachePath, ex.what()); } cb(response); } else { try { if (std::filesystem::exists(cachePath)) { JAMI_WARNING("Failed to download url, using cached data"); std::string data; { std::lock_guard lk(dhtnet::fileutils::getFileLock(cachePath)); data = fileutils::loadTextFile(cachePath); } dht::http::Response ret; ret.body = std::move(data); ret.status_code = 200; cb(ret); } else throw std::runtime_error("No cached data"); } catch (...) { cb(response); } } if (auto req = response.request.lock()) if (auto sthis = w.lock()) sthis->requests_.erase(req); }); sthis->requests_.emplace(req); req->send(); } } }); } void JamiAccount::loadCachedProxyServer(std::function<void(const std::string& proxy)> cb) { const auto& conf = config(); if (conf.proxyEnabled and proxyServerCached_.empty()) { JAMI_DEBUG("[Account {:s}] loading DHT proxy URL: {:s}", getAccountID(), conf.proxyListUrl); if (conf.proxyListUrl.empty() or not conf.proxyListEnabled) { cb(getDhtProxyServer(conf.proxyServer)); } else { loadCachedUrl(conf.proxyListUrl, cachePath_ / "dhtproxylist", std::chrono::hours(24 * 3), [w = weak(), cb = std::move(cb)](const dht::http::Response& response) { if (auto sthis = w.lock()) { if (response.status_code == 200) { cb(sthis->getDhtProxyServer(response.body)); } else { cb(sthis->getDhtProxyServer(sthis->config().proxyServer)); } } }); } } else { cb(proxyServerCached_); } } std::string JamiAccount::getDhtProxyServer(const std::string& serverList) { if (proxyServerCached_.empty()) { std::vector<std::string> proxys; // Split the list of servers std::sregex_iterator begin = {serverList.begin(), serverList.end(), PROXY_REGEX}, end; for (auto it = begin; it != end; ++it) { auto& match = *it; if (match[5].matched and match[6].matched) { try { auto start = std::stoi(match[5]), end = std::stoi(match[6]); for (auto p = start; p <= end; p++) proxys.emplace_back(match[1].str() + match[2].str() + ":" + std::to_string(p)); } catch (...) { JAMI_WARN("Malformed proxy, ignore it"); continue; } } else { proxys.emplace_back(match[0].str()); } } if (proxys.empty()) return {}; // Select one of the list as the current proxy. auto randIt = proxys.begin(); std::advance(randIt, std::uniform_int_distribution<unsigned long>(0, proxys.size() - 1)(rand)); proxyServerCached_ = *randIt; // Cache it! dhtnet::fileutils::check_dir(cachePath_, 0700); auto proxyCachePath = cachePath_ / "dhtproxy"; std::ofstream file(proxyCachePath); JAMI_DEBUG("Cache DHT proxy server: {}", proxyServerCached_); Json::Value node(Json::objectValue); node[getProxyConfigKey()] = proxyServerCached_; if (file.is_open()) file << node; else JAMI_WARNING("Unable to write into {}", proxyCachePath); } return proxyServerCached_; } MatchRank JamiAccount::matches(std::string_view userName, std::string_view server) const { if (not accountManager_ or not accountManager_->getInfo()) return MatchRank::NONE; if (userName == accountManager_->getInfo()->accountId || server == accountManager_->getInfo()->accountId || userName == accountManager_->getInfo()->deviceId) { JAMI_DBG("Matching account id in request with username %.*s", (int) userName.size(), userName.data()); return MatchRank::FULL; } else { return MatchRank::NONE; } } std::string JamiAccount::getFromUri() const { const std::string uri = "<sip:" + accountManager_->getInfo()->accountId + "@ring.dht>"; if (not config().displayName.empty()) return "\"" + config().displayName + "\" " + uri; return uri; } std::string JamiAccount::getToUri(const std::string& to) const { auto username = to; string_replace(username, "sip:", ""); return fmt::format("<sips:{};transport=tls>", username); } std::string getDisplayed(const std::string& conversationId, const std::string& messageId) { // implementing https://tools.ietf.org/rfc/rfc5438.txt return fmt::format( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" "<imdn><message-id>{}</message-id>\n" "{}" "<display-notification><status><displayed/></status></display-notification>\n" "</imdn>", messageId, conversationId.empty() ? "" : "<conversation>" + conversationId + "</conversation>"); } std::string getPIDF(const std::string& note) { // implementing https://datatracker.ietf.org/doc/html/rfc3863 return fmt::format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\">\n" " <tuple>\n" " <status>\n" " <basic>{}</basic>\n" " </status>\n" " </tuple>\n" "</presence>", note); } void JamiAccount::setIsComposing(const std::string& conversationUri, bool isWriting) { Uri uri(conversationUri); std::string conversationId = {}; if (uri.scheme() == Uri::Scheme::SWARM) { conversationId = uri.authority(); } else { return; } if (auto cm = convModule(true)) { if (auto typer = cm->getTypers(conversationId)) { if (isWriting) typer->addTyper(getUsername(), true); else typer->removeTyper(getUsername(), true); } } } bool JamiAccount::setMessageDisplayed(const std::string& conversationUri, const std::string& messageId, int status) { Uri uri(conversationUri); std::string conversationId = {}; if (uri.scheme() == Uri::Scheme::SWARM) conversationId = uri.authority(); auto sendMessage = status == (int) libjami::Account::MessageStates::DISPLAYED && isReadReceiptEnabled(); if (!conversationId.empty()) sendMessage &= convModule()->onMessageDisplayed(getUsername(), conversationId, messageId); if (sendMessage) sendInstantMessage(uri.authority(), {{MIME_TYPE_IMDN, getDisplayed(conversationId, messageId)}}); return true; } std::string JamiAccount::getContactHeader(const std::shared_ptr<SipTransport>& sipTransport) { if (sipTransport and sipTransport->get() != nullptr) { auto transport = sipTransport->get(); auto* td = reinterpret_cast<tls::AbstractSIPTransport::TransportData*>(transport); auto address = td->self->getLocalAddress().toString(true); bool reliable = transport->flag & PJSIP_TRANSPORT_RELIABLE; return fmt::format("\"{}\" <sips:{}{}{};transport={}>", config().displayName, id_.second->getId().toString(), address.empty() ? "" : "@", address, reliable ? "tls" : "dtls"); } else { JAMI_ERR("getContactHeader: no SIP transport provided"); return fmt::format("\"{}\" <sips:{}@ring.dht>", config().displayName, id_.second->getId().toString()); } } void JamiAccount::addContact(const std::string& uri, bool confirmed) { dht::InfoHash h(uri); if (not h) { JAMI_ERROR("addContact: invalid contact URI"); return; } auto conversation = convModule()->getOneToOneConversation(uri); if (!confirmed && conversation.empty()) conversation = convModule()->startConversation(ConversationMode::ONE_TO_ONE, h); std::unique_lock<std::recursive_mutex> lock(configurationMutex_); if (accountManager_) accountManager_->addContact(h, confirmed, conversation); else JAMI_WARNING("[Account {}] addContact: account not loaded", getAccountID()); } void JamiAccount::removeContact(const std::string& uri, bool ban) { std::lock_guard lock(configurationMutex_); if (accountManager_) accountManager_->removeContact(uri, ban); else JAMI_WARNING("[Account {}] removeContact: account not loaded", getAccountID()); } std::map<std::string, std::string> JamiAccount::getContactDetails(const std::string& uri) const { std::lock_guard lock(configurationMutex_); return accountManager_ ? accountManager_->getContactDetails(uri) : std::map<std::string, std::string> {}; } std::vector<std::map<std::string, std::string>> JamiAccount::getContacts(bool includeRemoved) const { std::lock_guard lock(configurationMutex_); if (not accountManager_) return {}; return accountManager_->getContacts(includeRemoved); } /* trust requests */ std::vector<std::map<std::string, std::string>> JamiAccount::getTrustRequests() const { std::lock_guard lock(configurationMutex_); return accountManager_ ? accountManager_->getTrustRequests() : std::vector<std::map<std::string, std::string>> {}; } bool JamiAccount::acceptTrustRequest(const std::string& from, bool includeConversation) { dht::InfoHash h(from); if (not h) { JAMI_ERROR("addContact: invalid contact URI"); return false; } std::unique_lock<std::recursive_mutex> lock(configurationMutex_); if (accountManager_) { if (!accountManager_->acceptTrustRequest(from, includeConversation)) { // Note: unused for swarm // Typically the case where the trust request doesn't exists, only incoming DHT messages return accountManager_->addContact(h, true); } return true; } JAMI_WARNING("[Account {}] acceptTrustRequest: account not loaded", getAccountID()); return false; } bool JamiAccount::discardTrustRequest(const std::string& from) { // Remove 1:1 generated conv requests auto requests = getTrustRequests(); for (const auto& req : requests) { if (req.at(libjami::Account::TrustRequest::FROM) == from) { convModule()->declineConversationRequest( req.at(libjami::Account::TrustRequest::CONVERSATIONID)); } } // Remove trust request std::lock_guard lock(configurationMutex_); if (accountManager_) return accountManager_->discardTrustRequest(from); JAMI_WARNING("[Account {:s}] discardTrustRequest: account not loaded", getAccountID()); return false; } void JamiAccount::declineConversationRequest(const std::string& conversationId) { auto peerId = convModule()->peerFromConversationRequest(conversationId); convModule()->declineConversationRequest(conversationId); if (!peerId.empty()) { std::lock_guard lock(configurationMutex_); if (auto info = accountManager_->getInfo()) { // Verify if we have a trust request with this peer + convId auto req = info->contacts->getTrustRequest(dht::InfoHash(peerId)); if (req.find(libjami::Account::TrustRequest::CONVERSATIONID) != req.end() && req.at(libjami::Account::TrustRequest::CONVERSATIONID) == conversationId) { accountManager_->discardTrustRequest(peerId); JAMI_DEBUG("[Account {:s}] declined trust request with {:s}", getAccountID(), peerId); } } } } void JamiAccount::sendTrustRequest(const std::string& to, const std::vector<uint8_t>& payload) { dht::InfoHash h(to); if (not h) { JAMI_ERROR("addContact: invalid contact URI"); return; } // Here we cache payload sent by the client auto requestPath = cachePath_ / "requests"; dhtnet::fileutils::recursive_mkdir(requestPath, 0700); auto cachedFile = requestPath / to; std::ofstream req(cachedFile, std::ios::trunc | std::ios::binary); if (!req.is_open()) { JAMI_ERROR("Unable to write data to {}", cachedFile); return; } if (not payload.empty()) { req.write(reinterpret_cast<const char*>(payload.data()), payload.size()); } if (payload.size() >= 64000) { JAMI_WARN() << "Trust request is too big. Remove payload"; } auto conversation = convModule()->getOneToOneConversation(to); if (conversation.empty()) conversation = convModule()->startConversation(ConversationMode::ONE_TO_ONE, h); if (not conversation.empty()) { std::lock_guard lock(configurationMutex_); if (accountManager_) accountManager_->sendTrustRequest(to, conversation, payload.size() >= 64000 ? std::vector<uint8_t> {} : payload); else JAMI_WARNING("[Account {}] sendTrustRequest: account not loaded", getAccountID()); } else JAMI_WARNING("[Account {}] sendTrustRequest: account not loaded", getAccountID()); } void JamiAccount::forEachDevice(const dht::InfoHash& to, std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op, std::function<void(bool)>&& end) { accountManager_->forEachDevice(to, std::move(op), std::move(end)); } uint64_t JamiAccount::sendTextMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t refreshToken, bool onlyConnected) { Uri uri(to); if (uri.scheme() == Uri::Scheme::SWARM) { sendInstantMessage(uri.authority(), payloads); return 0; } std::string toUri; try { toUri = parseJamiUri(to); } catch (...) { JAMI_ERROR("Failed to send a text message due to an invalid URI {}", to); return 0; } if (payloads.size() != 1) { JAMI_ERROR("Multi-part im is not supported yet by JamiAccount"); return 0; } return SIPAccountBase::sendTextMessage(toUri, deviceId, payloads, refreshToken, onlyConnected); } void JamiAccount::sendMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t token, bool retryOnTimeout, bool onlyConnected) { std::string toUri; try { toUri = parseJamiUri(to); } catch (...) { JAMI_ERROR("[Account {}] Failed to send a text message due to an invalid URI {}", getAccountID(), to); if (!onlyConnected) messageEngine_.onMessageSent(to, token, false, deviceId); return; } if (payloads.size() != 1) { JAMI_ERROR("Multi-part im is not supported"); if (!onlyConnected) messageEngine_.onMessageSent(toUri, token, false, deviceId); return; } auto devices = std::make_shared<std::set<DeviceId>>(); // Use the Message channel if available std::unique_lock clk(connManagerMtx_); auto* handler =static_cast<MessageChannelHandler*>(channelHandlers_[Uri::Scheme::MESSAGE].get()); if (!handler) { clk.unlock(); if (!onlyConnected) messageEngine_.onMessageSent(to, token, false, deviceId); return; } const auto& payload = *payloads.begin(); MessageChannelHandler::Message msg; msg.t = payload.first; msg.c = payload.second; auto device = deviceId.empty() ? DeviceId() : DeviceId(deviceId); if (deviceId.empty()) { bool sent = false; auto conns = handler->getChannels(toUri); clk.unlock(); for (const auto &conn: conns) { if (MessageChannelHandler::sendMessage(conn, msg)) { devices->emplace(conn->deviceId()); sent = true; } } if (sent && !onlyConnected) { runOnMainThread([w = weak(), to, token, deviceId]() { if (auto acc = w.lock()) acc->messageEngine_.onMessageSent(to, token, true, deviceId); }); } } else { if (auto conn = handler->getChannel(toUri, device)) { clk.unlock(); if (MessageChannelHandler::sendMessage(conn, msg)) { if (!onlyConnected) runOnMainThread([w = weak(), to, token, deviceId]() { if (auto acc = w.lock()) acc->messageEngine_.onMessageSent(to, token, true, deviceId); }); return; } } } if (clk) clk.unlock(); std::unique_lock lk(sipConnsMtx_); for (auto& [key, value]: sipConns_) { if (key.first != to or value.empty()) continue; if (!deviceId.empty() && key.second != device) continue; if (!devices->emplace(key.second).second) continue; auto& conn = value.back(); auto& channel = conn.channel; // Set input token into callback auto ctx = std::make_unique<TextMessageCtx>(); ctx->acc = weak(); ctx->to = to; ctx->deviceId = device; ctx->id = token; ctx->onlyConnected = onlyConnected; ctx->retryOnTimeout = retryOnTimeout; ctx->channel = channel; try { auto res = sendSIPMessage(conn, to, ctx.release(), token, payloads, [](void* token, pjsip_event* event) { std::shared_ptr<TextMessageCtx> c { (TextMessageCtx*) token}; auto code = event->body.tsx_state.tsx->status_code; runOnMainThread([c = std::move(c), code]() { if (c) { if (auto acc = c->acc.lock()) acc->onSIPMessageSent(std::move(c), code); } }); }); if (!res) { if (!onlyConnected) messageEngine_.onMessageSent(to, token, false, deviceId); devices->erase(key.second); continue; } } catch (const std::runtime_error& ex) { JAMI_WARNING("{}", ex.what()); if (!onlyConnected) messageEngine_.onMessageSent(to, token, false, deviceId); devices->erase(key.second); // Remove connection in incorrect state shutdownSIPConnection(channel, to, key.second); continue; } if (key.second == device) { return; } } lk.unlock(); if (onlyConnected) return; // We are unable to send the message directly, try connecting messageEngine_.onMessageSent(to, token, false, deviceId); // Get conversation id, which will be used by the iOS notification extension // to load the conversation. auto extractIdFromJson = [](const std::string& jsonData) -> std::string { Json::Value parsed; Json::CharReaderBuilder readerBuilder; auto reader = std::unique_ptr<Json::CharReader>(readerBuilder.newCharReader()); std::string errors; if (reader->parse(jsonData.c_str(), jsonData.c_str() + jsonData.size(), &parsed, &errors)) { auto value = parsed.get("id", Json::nullValue); if (value && value.isString()) { return value.asString(); } } else { JAMI_WARNING("Unable to parse jsonData to get conversation id"); } return ""; }; // get request type auto payload_type = msg.t; if (payload_type == MIME_TYPE_GIT) { std::string id = extractIdFromJson(msg.c); if (!id.empty()) { payload_type += "/" + id; } } if (deviceId.empty()) { auto toH = dht::InfoHash(toUri); // Find listening devices for this account accountManager_->forEachDevice(toH, [this, to, devices, payload_type, currentDevice = DeviceId(currentDeviceId())]( const std::shared_ptr<dht::crypto::PublicKey>& dev) { // Test if already sent auto deviceId = dev->getLongId(); if (!devices->emplace(deviceId).second || deviceId == currentDevice) { return; } // Else, ask for a channel to send the message requestSIPConnection(to, deviceId, payload_type); }); } else { requestSIPConnection(to, device, payload_type); } } void JamiAccount::onSIPMessageSent(const std::shared_ptr<TextMessageCtx>& ctx, int code) { if (code == PJSIP_SC_OK) { if (!ctx->onlyConnected) messageEngine_.onMessageSent(ctx->to, ctx->id, true, ctx->deviceId ? ctx->deviceId.toString() : ""); } else { // Note: This can be called from pjsip's eventloop while // sipConnsMtx_ is locked. So we should retrigger the shutdown. auto acc = ctx->acc.lock(); if (not acc) return; JAMI_WARN("Timeout when send a message, close current connection"); shutdownSIPConnection(ctx->channel, ctx->to, ctx->deviceId); // This MUST be done after closing the connection to avoid race condition // with messageEngine_ if (!ctx->onlyConnected) messageEngine_.onMessageSent(ctx->to, ctx->id, false, ctx->deviceId ? ctx->deviceId.toString() : ""); // In that case, the peer typically changed its connectivity. // After closing sockets with that peer, we try to re-connect to // that peer one time. if (ctx->retryOnTimeout) messageEngine_.onPeerOnline(ctx->to, ctx->deviceId ? ctx->deviceId.toString() : ""); } } dhtnet::IceTransportOptions JamiAccount::getIceOptions() const noexcept { return connectionManager_->getIceOptions(); } void JamiAccount::getIceOptions(std::function<void(dhtnet::IceTransportOptions&&)> cb) const noexcept { return connectionManager_->getIceOptions(std::move(cb)); } dhtnet::IpAddr JamiAccount::getPublishedIpAddress(uint16_t family) const { return connectionManager_->getPublishedIpAddress(family); } bool JamiAccount::setPushNotificationToken(const std::string& token) { if (SIPAccountBase::setPushNotificationToken(token)) { JAMI_WARNING("[Account {:s}] setPushNotificationToken: {:s}", getAccountID(), token); if (dht_) dht_->setPushNotificationToken(token); return true; } return false; } bool JamiAccount::setPushNotificationTopic(const std::string& topic) { if (SIPAccountBase::setPushNotificationTopic(topic)) { if (dht_) dht_->setPushNotificationTopic(topic); return true; } return false; } bool JamiAccount::setPushNotificationConfig(const std::map<std::string, std::string>& data) { if (SIPAccountBase::setPushNotificationConfig(data)) { if (dht_) { dht_->setPushNotificationPlatform(config_->platform); dht_->setPushNotificationTopic(config_->notificationTopic); dht_->setPushNotificationToken(config_->deviceKey); } return true; } return false; } /** * To be called by clients with relevant data when a push notification is received. */ void JamiAccount::pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data) { JAMI_WARNING("[Account {:s}] pushNotificationReceived: {:s}", getAccountID(), from); dht_->pushNotificationReceived(data); } std::string JamiAccount::getUserUri() const { #ifdef HAVE_RINGNS if (not registeredName_.empty()) return JAMI_URI_PREFIX + registeredName_; #endif return JAMI_URI_PREFIX + config().username; } std::vector<libjami::Message> JamiAccount::getLastMessages(const uint64_t& base_timestamp) { return SIPAccountBase::getLastMessages(base_timestamp); } void JamiAccount::startAccountPublish() { AccountPeerInfo info_pub; info_pub.accountId = dht::InfoHash(accountManager_->getInfo()->accountId); info_pub.displayName = config().displayName; peerDiscovery_->startPublish<AccountPeerInfo>(PEER_DISCOVERY_JAMI_SERVICE, info_pub); } void JamiAccount::startAccountDiscovery() { auto id = dht::InfoHash(accountManager_->getInfo()->accountId); peerDiscovery_->startDiscovery<AccountPeerInfo>( PEER_DISCOVERY_JAMI_SERVICE, [this, id](AccountPeerInfo&& v, dht::SockAddr&&) { std::lock_guard lc(discoveryMapMtx_); // Make sure that account itself will not be recorded if (v.accountId != id) { // Create or Find the old one auto& dp = discoveredPeers_[v.accountId]; dp.displayName = v.displayName; discoveredPeerMap_[v.accountId.toString()] = v.displayName; if (dp.cleanupTask) { dp.cleanupTask->cancel(); } else { // Avoid Repeat Reception of Same peer JAMI_LOG("Account discovered: {}: {}", v.displayName, v.accountId.to_c_str()); // Send Added Peer and corrsponding accoundID emitSignal<libjami::PresenceSignal::NearbyPeerNotification>(getAccountID(), v.accountId .toString(), 0, v.displayName); } dp.cleanupTask = Manager::instance().scheduler().scheduleIn( [w = weak(), p = v.accountId, a = v.displayName] { if (auto this_ = w.lock()) { { std::lock_guard lc(this_->discoveryMapMtx_); this_->discoveredPeers_.erase(p); this_->discoveredPeerMap_.erase(p.toString()); } // Send Deleted Peer emitSignal<libjami::PresenceSignal::NearbyPeerNotification>( this_->getAccountID(), p.toString(), 1, a); } JAMI_INFO("Account removed from discovery list: %s", a.c_str()); }, PEER_DISCOVERY_EXPIRATION); } }); } std::map<std::string, std::string> JamiAccount::getNearbyPeers() const { return discoveredPeerMap_; } void JamiAccount::sendProfileToPeers() { if (!connectionManager_) return; const auto& accountUri = accountManager_->getInfo()->accountId; for (const auto& connection : connectionManager_->getConnectionList()) { const auto& device = connection.at("device"); const auto& peer = connection.at("peer"); if (peer == accountUri) { sendProfile("", accountUri, device); continue; } const auto& conversationId = convModule()->getOneToOneConversation(peer); if (!conversationId.empty()) { sendProfile(conversationId, peer, device); } } } std::map<std::string, std::string> JamiAccount::getProfileVcard() const { const auto& path = idPath_ / "profile.vcf"; if (!std::filesystem::exists(path)) { return {}; } return vCard::utils::toMap(fileutils::loadTextFile(path)); } void JamiAccount::updateProfile(const std::string& displayName, const std::string& avatar, const uint64_t& flag) { const auto& accountUri = accountManager_->getInfo()->accountId; const auto& path = profilePath(); const auto& profiles = idPath_ / "profiles"; try { if (!std::filesystem::exists(profiles)) { std::filesystem::create_directories(profiles); } } catch (const std::exception& e) { JAMI_ERROR("Failed to create profiles directory: {}", e.what()); return; } const auto& vCardPath = profiles / fmt::format("{}.vcf", base64::encode(accountUri)); const std::filesystem::path& tmpPath = vCardPath.string() + ".tmp"; auto profile = getProfileVcard(); if (profile.empty()) { profile = vCard::utils::initVcard(); } profile["FN"] = displayName; editConfig([&](JamiAccountConfig& config) { config.displayName = displayName; }); emitSignal<libjami::ConfigurationSignal::AccountDetailsChanged>(getAccountID(), getAccountDetails()); if (flag == 0) { const auto& avatarPath = std::filesystem::path(avatar); if (std::filesystem::exists(avatarPath)) { try { const auto& base64 = jami::base64::encode(fileutils::loadFile(avatarPath)); profile["PHOTO;ENCODING=BASE64;TYPE=PNG"] = base64; } catch (const std::exception& e) { JAMI_ERROR("Failed to load avatar: {}", e.what()); } } else if (avatarPath.empty()) { profile["PHOTO;ENCODING=BASE64;TYPE=PNG"] = ""; } } else if (flag == 1) { profile["PHOTO;ENCODING=BASE64;TYPE=PNG"] = avatar; } // nothing happens to the profile photo if the avatarPath is invalid // and not empty. So far it seems to be the best default behavior. const std::string& vCard = vCard::utils::toString(profile); try { std::ofstream file(tmpPath); if (file.is_open()) { file << vCard; file.close(); std::filesystem::rename(tmpPath, vCardPath); fileutils::createFileLink(path, vCardPath); sendProfileToPeers(); emitSignal<libjami::ConfigurationSignal::ProfileReceived>(getAccountID(), accountUri, path.string()); } else { JAMI_ERROR("Unable to open file for writing: {}", tmpPath.string()); } } catch (const std::exception& e) { JAMI_ERROR("Error writing profile: {}", e.what()); } } void JamiAccount::setActiveCodecs(const std::vector<unsigned>& list) { Account::setActiveCodecs(list); if (!hasActiveCodec(MEDIA_AUDIO)) setCodecActive(AV_CODEC_ID_OPUS); if (!hasActiveCodec(MEDIA_VIDEO)) { setCodecActive(AV_CODEC_ID_HEVC); setCodecActive(AV_CODEC_ID_H264); setCodecActive(AV_CODEC_ID_VP8); } config_->activeCodecs = getActiveCodecs(MEDIA_ALL); } void JamiAccount::sendInstantMessage(const std::string& convId, const std::map<std::string, std::string>& msg) { auto members = convModule()->getConversationMembers(convId); if (convId.empty() && members.empty()) { // TODO remove, it's for old API for contacts sendTextMessage(convId, "", msg); return; } for (const auto& m : members) { const auto& uri = m.at("uri"); auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}(rand); // Announce to all members that a new message is sent sendMessage(uri, "", msg, token, false, true); } } bool JamiAccount::handleMessage(const std::string& from, const std::pair<std::string, std::string>& m) { if (m.first == MIME_TYPE_GIT) { Json::Value json; std::string err; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(m.second.data(), m.second.data() + m.second.size(), &json, &err)) { JAMI_ERROR("Unable to parse server response: {}", err); return false; } std::string deviceId = json["deviceId"].asString(); std::string id = json["id"].asString(); std::string commit = json["commit"].asString(); // fetchNewCommits will do heavy stuff like fetching, avoid to block SIP socket dht::ThreadPool::io().run([w = weak(), from, deviceId, id, commit] { if (auto shared = w.lock()) { if (auto cm = shared->convModule()) cm->fetchNewCommits(from, deviceId, id, commit); } }); return true; } else if (m.first == MIME_TYPE_INVITE) { convModule()->onNeedConversationRequest(from, m.second); return true; } else if (m.first == MIME_TYPE_INVITE_JSON) { Json::Value json; std::string err; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(m.second.data(), m.second.data() + m.second.size(), &json, &err)) { JAMI_ERROR("Unable to parse server response: {}", err); return false; } convModule()->onConversationRequest(from, json); return true; } else if (m.first == MIME_TYPE_IM_COMPOSING) { try { static const std::regex COMPOSING_REGEX("<state>\\s*(\\w+)\\s*<\\/state>"); std::smatch matched_pattern; std::regex_search(m.second, matched_pattern, COMPOSING_REGEX); bool isComposing {false}; if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { isComposing = matched_pattern[1] == "active"; } static const std::regex CONVID_REGEX("<conversation>\\s*(\\w+)\\s*<\\/conversation>"); std::regex_search(m.second, matched_pattern, CONVID_REGEX); std::string conversationId = ""; if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { conversationId = matched_pattern[1]; } if (!conversationId.empty()) { if (auto cm = convModule(true)) { if (auto typer = cm->getTypers(conversationId)) { if (isComposing) typer->addTyper(from); else typer->removeTyper(from); } } } return true; } catch (const std::exception& e) { JAMI_WARNING("Error parsing composing state: {}", e.what()); } } else if (m.first == MIME_TYPE_IMDN) { try { static const std::regex IMDN_MSG_ID_REGEX("<message-id>\\s*(\\w+)\\s*<\\/message-id>"); std::smatch matched_pattern; std::regex_search(m.second, matched_pattern, IMDN_MSG_ID_REGEX); std::string messageId; if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { messageId = matched_pattern[1]; } else { JAMI_WARNING("Message displayed: unable to parse message ID"); return false; } static const std::regex STATUS_REGEX("<status>\\s*<(\\w+)\\/>\\s*<\\/status>"); std::regex_search(m.second, matched_pattern, STATUS_REGEX); bool isDisplayed {false}; if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { isDisplayed = matched_pattern[1] == "displayed"; } else { JAMI_WARNING("Message displayed: unable to parse status"); return false; } static const std::regex CONVID_REGEX("<conversation>\\s*(\\w+)\\s*<\\/conversation>"); std::regex_search(m.second, matched_pattern, CONVID_REGEX); std::string conversationId = ""; if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { conversationId = matched_pattern[1]; } if (!isReadReceiptEnabled()) return true; if (isDisplayed) { if (convModule()->onMessageDisplayed(from, conversationId, messageId)) { JAMI_DEBUG("[message {}] Displayed by peer", messageId); emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>( accountID_, conversationId, from, messageId, static_cast<int>(libjami::Account::MessageStates::DISPLAYED)); } } return true; } catch (const std::exception& e) { JAMI_ERROR("Error parsing display notification: {}", e.what()); } } else if (m.first == MIME_TYPE_PIDF) { std::smatch matched_pattern; static const std::regex BASIC_REGEX("<basic>([\\w\\s]+)<\\/basic>"); std::regex_search(m.second, matched_pattern, BASIC_REGEX); std::string customStatus {}; if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { customStatus = matched_pattern[1]; emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(), from, static_cast<int>( PresenceState::CONNECTED), customStatus); return true; } else { JAMI_WARNING("Presence: unable to parse status"); } } return false; } void JamiAccount::callConnectionClosed(const DeviceId& deviceId, bool eraseDummy) { std::function<void(const DeviceId&, bool)> cb; { std::lock_guard lk(onConnectionClosedMtx_); auto it = onConnectionClosed_.find(deviceId); if (it != onConnectionClosed_.end()) { if (eraseDummy) { cb = std::move(it->second); onConnectionClosed_.erase(it); } else { // In this case a new subcall is created and the callback // will be re-called once with eraseDummy = true cb = it->second; } } } dht::ThreadPool::io().run( [w = weak(), cb = std::move(cb), id = deviceId, erase = std::move(eraseDummy)] { if (auto acc = w.lock()) { if (cb) cb(id, erase); } }); } void JamiAccount::requestMessageConnection(const std::string& peerId, const DeviceId& deviceId, const std::string& connectionType, bool forceNewConnection) { auto* handler = static_cast<MessageChannelHandler*>(channelHandlers_[Uri::Scheme::MESSAGE].get()); if (deviceId) { if (auto connected = handler->getChannel(peerId, deviceId)) { return; } } else { auto connected = handler->getChannels(peerId); if (!connected.empty()) { return; } } handler->connect(deviceId, "", [w = weak(), peerId]( std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId& deviceId) { if (socket) if (auto acc = w.lock()) { acc->messageEngine_.onPeerOnline(peerId); acc->messageEngine_.onPeerOnline(peerId, deviceId.toString(), true); } }); } void JamiAccount::requestSIPConnection(const std::string& peerId, const DeviceId& deviceId, const std::string& connectionType, bool forceNewConnection, const std::shared_ptr<SIPCall>& pc) { requestMessageConnection(peerId, deviceId, connectionType, forceNewConnection); if (peerId == getUsername()) { if (!syncModule()->isConnected(deviceId)) channelHandlers_[Uri::Scheme::SYNC] ->connect(deviceId, "", [](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId& deviceId) {}); } JAMI_LOG("[Account {}] Request SIP connection to peer {} on device {}", getAccountID(), peerId, deviceId); // If a connection already exists or is in progress, no need to do this std::lock_guard lk(sipConnsMtx_); auto id = std::make_pair(peerId, deviceId); if (sipConns_.find(id) != sipConns_.end()) { JAMI_LOG("[Account {}] A SIP connection with {} already exists", getAccountID(), deviceId); return; } // If not present, create it std::lock_guard lkCM(connManagerMtx_); if (!connectionManager_) return; // Note, Even if we send 50 "sip" request, the connectionManager_ will only use one socket. // however, this will still ask for multiple channels, so only ask // if there is no pending request if (!forceNewConnection && connectionManager_->isConnecting(deviceId, "sip")) { JAMI_LOG("[Account {}] Already connecting to {}", getAccountID(), deviceId); return; } JAMI_LOG("[Account {}] Ask {} for a new SIP channel", getAccountID(), deviceId); connectionManager_->connectDevice( deviceId, "sip", [w = weak(), id = std::move(id), pc = std::move(pc)](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId&) { if (socket) return; auto shared = w.lock(); if (!shared) return; // If this is triggered, this means that the // connectDevice didn't get any response from the DHT. // Stop searching pending call. shared->callConnectionClosed(id.second, true); if (pc) pc->onFailure(); }, false, forceNewConnection, connectionType); } bool JamiAccount::isConnectedWith(const DeviceId& deviceId) const { std::lock_guard lkCM(connManagerMtx_); if (connectionManager_) return connectionManager_->isConnected(deviceId); return false; } void JamiAccount::sendPresenceNote(const std::string& note) { if (auto info = accountManager_->getInfo()) { if (!info || !info->contacts) return; presenceNote_ = note; auto contacts = info->contacts->getContacts(); std::vector<SipConnectionKey> keys; { std::lock_guard lk(sipConnsMtx_); for (auto& [key, conns] : sipConns_) { keys.push_back(key); } } auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}(rand); std::map<std::string, std::string> msg = {{MIME_TYPE_PIDF, getPIDF(presenceNote_)}}; for (auto& key : keys) { sendMessage(key.first, key.second.toString(), msg, token, false, true); } } } void JamiAccount::sendProfile(const std::string& convId, const std::string& peerUri, const std::string& deviceId) { auto accProfilePath = profilePath(); if (not std::filesystem::is_regular_file(accProfilePath)) return; auto currentSha3 = fileutils::sha3File(accProfilePath); // VCard sync for peerUri if (not needToSendProfile(peerUri, deviceId, currentSha3)) { JAMI_DEBUG("Peer {} already got an up-to-date vcard", peerUri); return; } // We need a new channel transferFile(convId, accProfilePath.string(), deviceId, "profile.vcf", "", 0, 0, currentSha3, fileutils::lastWriteTimeInSeconds(accProfilePath), [accId = getAccountID(), peerUri, deviceId]() { // Mark the VCard as sent auto sendDir = fileutils::get_cache_dir() / accId / "vcard" / peerUri; auto path = sendDir / deviceId; dhtnet::fileutils::recursive_mkdir(sendDir); std::lock_guard lock(dhtnet::fileutils::getFileLock(path)); if (std::filesystem::is_regular_file(path)) return; std::ofstream p(path); }); } bool JamiAccount::needToSendProfile(const std::string& peerUri, const std::string& deviceId, const std::string& sha3Sum) { std::string previousSha3 {}; auto vCardPath = cachePath_ / "vcard"; auto sha3Path = vCardPath / "sha3"; dhtnet::fileutils::check_dir(vCardPath, 0700); try { previousSha3 = fileutils::loadTextFile(sha3Path); } catch (...) { fileutils::saveFile(sha3Path, (const uint8_t*) sha3Sum.data(), sha3Sum.size(), 0600); return true; } if (sha3Sum != previousSha3) { // Incorrect sha3 stored. Update it dhtnet::fileutils::removeAll(vCardPath, true); dhtnet::fileutils::check_dir(vCardPath, 0700); fileutils::saveFile(sha3Path, (const uint8_t*) sha3Sum.data(), sha3Sum.size(), 0600); return true; } auto peerPath = vCardPath / peerUri; dhtnet::fileutils::recursive_mkdir(peerPath); return not std::filesystem::is_regular_file(peerPath / deviceId); } bool JamiAccount::sendSIPMessage(SipConnection& conn, const std::string& to, void* ctx, uint64_t token, const std::map<std::string, std::string>& data, pjsip_endpt_send_callback cb) { auto transport = conn.transport; auto channel = conn.channel; if (!channel) throw std::runtime_error( "A SIP transport exists without Channel, this is a bug. Please report"); auto remote_address = channel->getRemoteAddress(); if (!remote_address) return false; // Build SIP Message // "deviceID@IP" auto toURI = getToUri(fmt::format("{}@{}", to, remote_address.toString(true))); std::string from = getFromUri(); // Build SIP message constexpr pjsip_method msg_method = {PJSIP_OTHER_METHOD, sip_utils::CONST_PJ_STR(sip_utils::SIP_METHODS::MESSAGE)}; pj_str_t pjFrom = sip_utils::CONST_PJ_STR(from); pj_str_t pjTo = sip_utils::CONST_PJ_STR(toURI); // Create request. pjsip_tx_data* tdata = nullptr; pj_status_t status = pjsip_endpt_create_request(link_.getEndpoint(), &msg_method, &pjTo, &pjFrom, &pjTo, nullptr, nullptr, -1, nullptr, &tdata); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to create request: {}", sip_utils::sip_strerror(status)); return false; } // Add Date Header. pj_str_t date_str; constexpr auto key = sip_utils::CONST_PJ_STR("Date"); pjsip_hdr* hdr; auto time = std::time(nullptr); auto date = std::ctime(&time); // the erase-remove idiom for a cstring, removes _all_ new lines with in date *std::remove(date, date + strlen(date), '\n') = '\0'; // Add Header hdr = reinterpret_cast<pjsip_hdr*>( pjsip_date_hdr_create(tdata->pool, &key, pj_cstr(&date_str, date))); pjsip_msg_add_hdr(tdata->msg, hdr); // https://tools.ietf.org/html/rfc5438#section-6.3 auto token_str = to_hex_string(token); auto pjMessageId = sip_utils::CONST_PJ_STR(token_str); hdr = reinterpret_cast<pjsip_hdr*>( pjsip_generic_string_hdr_create(tdata->pool, &STR_MESSAGE_ID, &pjMessageId)); pjsip_msg_add_hdr(tdata->msg, hdr); // Add user-agent header sip_utils::addUserAgentHeader(getUserAgentName(), tdata); // Init tdata const pjsip_tpselector tp_sel = SIPVoIPLink::getTransportSelector(transport->get()); status = pjsip_tx_data_set_transport(tdata, &tp_sel); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to create request: {}", sip_utils::sip_strerror(status)); return false; } im::fillPJSIPMessageBody(*tdata, data); // Because pjsip_endpt_send_request can take quite some time, move it in a io thread to avoid to block dht::ThreadPool::io().run([w = weak(), tdata, ctx, cb = std::move(cb)] { auto shared = w.lock(); if (!shared) return; auto status = pjsip_endpt_send_request(shared->link_.getEndpoint(), tdata, -1, ctx, cb); if (status != PJ_SUCCESS) JAMI_ERROR("Unable to send request: {}", sip_utils::sip_strerror(status)); }); return true; } void JamiAccount::clearProfileCache(const std::string& peerUri) { std::error_code ec; std::filesystem::remove_all(cachePath_ / "vcard" / peerUri, ec); } std::filesystem::path JamiAccount::profilePath() const { return idPath_ / "profile.vcf"; } void JamiAccount::cacheSIPConnection(std::shared_ptr<dhtnet::ChannelSocket>&& socket, const std::string& peerId, const DeviceId& deviceId) { std::unique_lock lk(sipConnsMtx_); // Verify that the connection is not already cached SipConnectionKey key(peerId, deviceId); auto& connections = sipConns_[key]; auto conn = std::find_if(connections.begin(), connections.end(), [&](const auto& v) { return v.channel == socket; }); if (conn != connections.end()) { JAMI_WARNING("[Account {}] Channel socket already cached with this peer", getAccountID()); return; } // Convert to SIP transport auto onShutdown = [w = weak(), peerId, key, socket]() { dht::ThreadPool::io().run([w = std::move(w), peerId, key, socket] { auto shared = w.lock(); if (!shared) return; shared->shutdownSIPConnection(socket, key.first, key.second); // The connection can be closed during the SIP initialization, so // if this happens, the request should be re-sent to ask for a new // SIP channel to make the call pass through shared->callConnectionClosed(key.second, false); }); }; auto sip_tr = link_.sipTransportBroker->getChanneledTransport(shared(), socket, std::move(onShutdown)); if (!sip_tr) { JAMI_ERROR("No channeled transport found"); return; } // Store the connection connections.emplace_back(SipConnection {sip_tr, socket}); JAMI_WARNING("[Account {:s}] New SIP channel opened with {:s}", getAccountID(), deviceId); lk.unlock(); dht::ThreadPool::io().run([w = weak(), peerId, deviceId] { if (auto shared = w.lock()) { if (shared->presenceNote_ != "") { // If a presence note is set, send it to this device. auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}( shared->rand); std::map<std::string, std::string> msg = { {MIME_TYPE_PIDF, getPIDF(shared->presenceNote_)}}; shared->sendMessage(peerId, deviceId.toString(), msg, token, false, true); } shared->convModule()->syncConversations(peerId, deviceId.toString()); } }); // Retry messages messageEngine_.onPeerOnline(peerId); messageEngine_.onPeerOnline(peerId, deviceId.toString(), true); // Connect pending calls forEachPendingCall(deviceId, [&](const auto& pc) { if (pc->getConnectionState() != Call::ConnectionState::TRYING and pc->getConnectionState() != Call::ConnectionState::PROGRESSING) return; pc->setSipTransport(sip_tr, getContactHeader(sip_tr)); pc->setState(Call::ConnectionState::PROGRESSING); if (auto remote_address = socket->getRemoteAddress()) { try { onConnectedOutgoingCall(pc, peerId, remote_address); } catch (const VoipLinkException&) { // In this case, the main scenario is that SIPStartCall failed because // the ICE is dead and the TLS session didn't send any packet on that dead // link (connectivity change, killed by the os, etc) // Here, we don't need to do anything, the TLS will fail and will delete // the cached transport } } }); auto& state = presenceState_[peerId]; if (state != PresenceState::CONNECTED) { state = PresenceState::CONNECTED; emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(), peerId, static_cast<int>( PresenceState::CONNECTED), ""); } } void JamiAccount::shutdownSIPConnection(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const std::string& peerId, const DeviceId& deviceId) { std::unique_lock lk(sipConnsMtx_); SipConnectionKey key(peerId, deviceId); auto it = sipConns_.find(key); if (it != sipConns_.end()) { auto& conns = it->second; conns.erase(std::remove_if(conns.begin(), conns.end(), [&](auto v) { return v.channel == channel; }), conns.end()); if (conns.empty()) { sipConns_.erase(it); // If all devices of an account are disconnected, we need to update the presence state auto it = std::find_if(sipConns_.begin(), sipConns_.end(), [&](const auto& v) { return v.first.first == peerId; }); if (it == sipConns_.end()) { auto& state = presenceState_[peerId]; if (state == PresenceState::CONNECTED) { std::lock_guard lock(buddyInfoMtx); auto buddy = trackedBuddies_.find(dht::InfoHash(peerId)); if (buddy == trackedBuddies_.end()) state = PresenceState::DISCONNECTED; else state = buddy->second.devices_cnt > 0 ? PresenceState::AVAILABLE : PresenceState::DISCONNECTED; emitSignal<libjami::PresenceSignal::NewBuddyNotification>(getAccountID(), peerId, static_cast<int>( state), ""); } } } } lk.unlock(); // Shutdown after removal to let the callbacks do stuff if needed if (channel) channel->shutdown(); } std::string_view JamiAccount::currentDeviceId() const { if (!accountManager_ or not accountManager_->getInfo()) return {}; return accountManager_->getInfo()->deviceId; } std::shared_ptr<TransferManager> JamiAccount::dataTransfer(const std::string& id) { if (id.empty()) return nonSwarmTransferManager_; return convModule()->dataTransfer(id); } void JamiAccount::monitor() { JAMI_DEBUG("[Account {:s}] Monitor connections", getAccountID()); JAMI_DEBUG("[Account {:s}] Using proxy: {:s}", getAccountID(), proxyServerCached_); if (auto cm = convModule()) cm->monitor(); std::lock_guard lkCM(connManagerMtx_); if (connectionManager_) connectionManager_->monitor(); } std::vector<std::map<std::string, std::string>> JamiAccount::getConnectionList(const std::string& conversationId) { std::lock_guard lkCM(connManagerMtx_); if (connectionManager_ && conversationId.empty()) { return connectionManager_->getConnectionList(); } else if (connectionManager_ && convModule_) { std::vector<std::map<std::string, std::string>> connectionList; if (auto conv = convModule_->getConversation(conversationId)) { for (const auto& deviceId : conv->getDeviceIdList()) { auto connections = connectionManager_->getConnectionList(deviceId); connectionList.reserve(connectionList.size() + connections.size()); std::move(connections.begin(), connections.end(), std::back_inserter(connectionList)); } } return connectionList; } else { return {}; } } std::vector<std::map<std::string, std::string>> JamiAccount::getChannelList(const std::string& connectionId) { std::lock_guard lkCM(connManagerMtx_); if (!connectionManager_) return {}; return connectionManager_->getChannelList(connectionId); } void JamiAccount::sendFile(const std::string& conversationId, const std::filesystem::path& path, const std::string& name, const std::string& replyTo) { if (!std::filesystem::is_regular_file(path)) { JAMI_ERROR("Invalid filename '{}'", path); return; } // NOTE: this sendMessage is in a computation thread because // sha3sum can take quite some time to computer if the user decide // to send a big file dht::ThreadPool::computation().run([w = weak(), conversationId, path, name, replyTo]() { if (auto shared = w.lock()) { Json::Value value; auto tid = jami::generateUID(shared->rand); value["tid"] = std::to_string(tid); value["displayName"] = name.empty() ? path.filename().string() : name; value["totalSize"] = std::to_string(fileutils::size(path)); value["sha3sum"] = fileutils::sha3File(path); value["type"] = "application/data-transfer+json"; shared->convModule()->sendMessage( conversationId, std::move(value), replyTo, true, [accId = shared->getAccountID(), conversationId, tid, path]( const std::string& commitId) { // Create a symlink to answer to re-ask auto filelinkPath = fileutils::get_data_dir() / accId / "conversation_data" / conversationId / (commitId + "_" + std::to_string(tid)); filelinkPath += path.extension(); if (path != filelinkPath && !std::filesystem::is_symlink(filelinkPath)) { if (!fileutils::createFileLink(filelinkPath, path, true)) { JAMI_WARNING( "Unable to create symlink for file transfer {} - {}. Copy file", filelinkPath, path); if (!std::filesystem::copy_file(path, filelinkPath)) { JAMI_ERROR("Unable to copy file for file transfer {} - {}", filelinkPath, path); // Signal to notify clients that the operation failed. // The fileId field sends the filePath. // libjami::DataTransferEventCode::unsupported (2) is unused elsewhere. emitSignal<libjami::DataTransferSignal::DataTransferEvent>( accId, conversationId, commitId, path.u8string(), uint32_t(libjami::DataTransferEventCode::invalid)); } else { // Signal to notify clients that the file is copied and can be // safely deleted. The fileId field sends the filePath. // libjami::DataTransferEventCode::created (1) is unused elsewhere. emitSignal<libjami::DataTransferSignal::DataTransferEvent>( accId, conversationId, commitId, path.u8string(), uint32_t(libjami::DataTransferEventCode::created)); } } else { emitSignal<libjami::DataTransferSignal::DataTransferEvent>( accId, conversationId, commitId, path.u8string(), uint32_t(libjami::DataTransferEventCode::created)); } } }); } }); } void JamiAccount::transferFile(const std::string& conversationId, const std::string& path, const std::string& deviceId, const std::string& fileId, const std::string& interactionId, size_t start, size_t end, const std::string& sha3Sum, uint64_t lastWriteTime, std::function<void()> onFinished) { std::string modified; if (lastWriteTime != 0) { modified = fmt::format("&modified={}", lastWriteTime); } auto fid = fileId == "profile.vcf" ? fmt::format("profile.vcf?sha3={}{}", sha3Sum, modified) : fileId; auto channelName = conversationId.empty() ? fmt::format("{}profile.vcf?sha3={}{}", DATA_TRANSFER_SCHEME, sha3Sum, modified) : fmt::format("{}{}/{}/{}", DATA_TRANSFER_SCHEME, conversationId, currentDeviceId(), fid); std::lock_guard lkCM(connManagerMtx_); if (!connectionManager_) return; connectionManager_ ->connectDevice(DeviceId(deviceId), channelName, [this, conversationId, path = std::move(path), fileId, interactionId, start, end, onFinished = std::move( onFinished)](std::shared_ptr<dhtnet::ChannelSocket> socket, const DeviceId&) { if (!socket) return; dht::ThreadPool::io().run([w = weak(), path = std::move(path), socket = std::move(socket), conversationId = std::move(conversationId), fileId, interactionId, start, end, onFinished = std::move(onFinished)] { if (auto shared = w.lock()) if (auto dt = shared->dataTransfer(conversationId)) dt->transferFile(socket, fileId, interactionId, path, start, end, std::move(onFinished)); }); }); } void JamiAccount::askForFileChannel(const std::string& conversationId, const std::string& deviceId, const std::string& interactionId, const std::string& fileId, size_t start, size_t end) { auto tryDevice = [=](const auto& did) { std::lock_guard lkCM(connManagerMtx_); if (!connectionManager_) return; auto channelName = fmt::format("{}{}/{}/{}", DATA_TRANSFER_SCHEME, conversationId, currentDeviceId(), fileId); if (start != 0 || end != 0) { channelName += fmt::format("?start={}&end={}", start, end); } // We can avoid to negotiate new sessions, as the file notif // probably come from an online device or last connected device. connectionManager_->connectDevice( did, channelName, [w = weak(), conversationId, fileId, interactionId](std::shared_ptr<dhtnet::ChannelSocket> channel, const DeviceId&) { if (!channel) return; dht::ThreadPool::io().run([w, conversationId, channel, fileId, interactionId] { auto shared = w.lock(); if (!shared) return; auto dt = shared->dataTransfer(conversationId); if (!dt) return; if (interactionId.empty()) dt->onIncomingProfile(channel); else dt->onIncomingFileTransfer(fileId, channel); }); }, false); }; if (!deviceId.empty()) { // Only ask for device tryDevice(DeviceId(deviceId)); } else { // Only ask for connected devices. For others we will try // on new peer online for (const auto& m : convModule()->getConversationMembers(conversationId)) { accountManager_->forEachDevice(dht::InfoHash(m.at("uri")), [tryDevice = std::move(tryDevice)]( const std::shared_ptr<dht::crypto::PublicKey>& dev) { tryDevice(dev->getLongId()); }); } } } void JamiAccount::askForProfile(const std::string& conversationId, const std::string& deviceId, const std::string& memberUri) { std::lock_guard lkCM(connManagerMtx_); if (!connectionManager_) return; auto channelName = fmt::format("{}{}/profile/{}.vcf", DATA_TRANSFER_SCHEME, conversationId, memberUri); // We can avoid to negotiate new sessions, as the file notif // probably come from an online device or last connected device. connectionManager_->connectDevice( DeviceId(deviceId), channelName, [this, conversationId](std::shared_ptr<dhtnet::ChannelSocket> channel, const DeviceId&) { if (!channel) return; dht::ThreadPool::io().run([w = weak(), conversationId, channel] { if (auto shared = w.lock()) if (auto dt = shared->dataTransfer(conversationId)) dt->onIncomingProfile(channel); }); }, false); } void JamiAccount::initConnectionManager() { if (!nonSwarmTransferManager_) nonSwarmTransferManager_ = std::make_shared<TransferManager>(accountID_, config().username, "", dht::crypto::getDerivedRandomEngine(rand)); if (!connectionManager_) { auto connectionManagerConfig = std::make_shared<dhtnet::ConnectionManager::Config>(); connectionManagerConfig->ioContext = Manager::instance().ioContext(); connectionManagerConfig->dht = dht(); connectionManagerConfig->certStore = certStore_; connectionManagerConfig->id = identity(); connectionManagerConfig->upnpCtrl = upnpCtrl_; connectionManagerConfig->turnServer = config().turnServer; connectionManagerConfig->upnpEnabled = config().upnpEnabled; connectionManagerConfig->turnServerUserName = config().turnServerUserName; connectionManagerConfig->turnServerPwd = config().turnServerPwd; connectionManagerConfig->turnServerRealm = config().turnServerRealm; connectionManagerConfig->turnEnabled = config().turnEnabled; connectionManagerConfig->cachePath = cachePath_; connectionManagerConfig->logger = Logger::dhtLogger(); connectionManagerConfig->factory = Manager::instance().getIceTransportFactory(); connectionManagerConfig->turnCache = turnCache_; connectionManagerConfig->rng = std::make_unique<std::mt19937_64>( dht::crypto::getDerivedRandomEngine(rand)); connectionManager_ = std::make_unique<dhtnet::ConnectionManager>(connectionManagerConfig); channelHandlers_[Uri::Scheme::SWARM] = std::make_unique<SwarmChannelHandler>(shared(), *connectionManager_.get()); channelHandlers_[Uri::Scheme::GIT] = std::make_unique<ConversationChannelHandler>(shared(), *connectionManager_.get()); channelHandlers_[Uri::Scheme::SYNC] = std::make_unique<SyncChannelHandler>(shared(), *connectionManager_.get()); channelHandlers_[Uri::Scheme::DATA_TRANSFER] = std::make_unique<TransferChannelHandler>(shared(), *connectionManager_.get()); channelHandlers_[Uri::Scheme::MESSAGE] = std::make_unique<MessageChannelHandler>(shared(), *connectionManager_.get()); #if TARGET_OS_IOS connectionManager_->oniOSConnected([&](const std::string& connType, dht::InfoHash peer_h) { if ((connType == "videoCall" || connType == "audioCall") && jami::Manager::instance().isIOSExtension) { bool hasVideo = connType == "videoCall"; emitSignal<libjami::ConversationSignal::CallConnectionRequest>("", peer_h.toString(), hasVideo); return true; } return false; }); #endif } } void JamiAccount::updateUpnpController() { Account::updateUpnpController(); if (connectionManager_) { auto config = connectionManager_->getConfig(); if (config) config->upnpCtrl = upnpCtrl_; } } } // namespace jami
179,722
C++
.cpp
4,096
29.900146
129
0.527257
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,807
conversationrepository.cpp
savoirfairelinux_jami-daemon/src/jamidht/conversationrepository.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "conversationrepository.h" #include "account_const.h" #include "base64.h" #include "jamiaccount.h" #include "fileutils.h" #include "gittransport.h" #include "string_utils.h" #include "client/ring_signal.h" #include "vcard.h" #include <ctime> #include <fstream> #include <future> #include <json/json.h> #include <regex> #include <exception> #include <optional> using namespace std::string_view_literals; constexpr auto DIFF_REGEX = " +\\| +[0-9]+.*"sv; constexpr size_t MAX_FETCH_SIZE {256 * 1024 * 1024}; // 256Mb namespace jami { #ifdef LIBJAMI_TESTABLE bool ConversationRepository::DISABLE_RESET = false; #endif static const std::regex regex_display_name("<|>"); inline std::string_view as_view(const git_blob* blob) { return std::string_view(static_cast<const char*>(git_blob_rawcontent(blob)), git_blob_rawsize(blob)); } inline std::string_view as_view(const GitObject& blob) { return as_view(reinterpret_cast<git_blob*>(blob.get())); } class ConversationRepository::Impl { public: Impl(const std::shared_ptr<JamiAccount>& account, const std::string& id) : account_(account) , id_(id) , accountId_(account->getAccountID()) , userId_(account->getUsername()) , deviceId_(account->currentDeviceId()) { conversationDataPath_ = fileutils::get_data_dir() / accountId_ / "conversation_data" / id_; membersCache_ = conversationDataPath_ / "members"; loadMembers(); if (members_.empty()) { initMembers(); } } void loadMembers() { try { // read file auto file = fileutils::loadFile(membersCache_); // load values msgpack::object_handle oh = msgpack::unpack((const char*) file.data(), file.size()); std::lock_guard lk {membersMtx_}; oh.get().convert(members_); } catch (const std::exception& e) { } } // Note: membersMtx_ needs to be locked when calling saveMembers void saveMembers() { std::ofstream file(membersCache_, std::ios::trunc | std::ios::binary); msgpack::pack(file, members_); if (onMembersChanged_) { std::set<std::string> memberUris; for (const auto& member : members_) { memberUris.emplace(member.uri); } onMembersChanged_(memberUris); } } OnMembersChanged onMembersChanged_ {}; // NOTE! We use temporary GitRepository to avoid to keep file opened (TODO check why // git_remote_fetch() leaves pack-data opened) GitRepository repository() const { auto path = fileutils::get_data_dir().string() + "/" + accountId_ + "/" + "conversations" + "/" + id_; git_repository* repo = nullptr; auto err = git_repository_open(&repo, path.c_str()); if (err < 0) { JAMI_ERROR("Unable to open git repository: {} ({})", path, git_error_last()->message); return {nullptr, git_repository_free}; } return {std::move(repo), git_repository_free}; } std::string getDisplayName() const { auto shared = account_.lock(); if (!shared) return {}; auto name = shared->getDisplayName(); if (name.empty()) name = deviceId_; return std::regex_replace(name, regex_display_name, ""); } GitSignature signature(); bool mergeFastforward(const git_oid* target_oid, int is_unborn); std::string createMergeCommit(git_index* index, const std::string& wanted_ref); bool validCommits(const std::vector<ConversationCommit>& commits) const; bool checkValidUserDiff(const std::string& userDevice, const std::string& commitId, const std::string& parentId) const; bool checkVote(const std::string& userDevice, const std::string& commitId, const std::string& parentId) const; bool checkEdit(const std::string& userDevice, const ConversationCommit& commit) const; bool isValidUserAtCommit(const std::string& userDevice, const std::string& commitId) const; bool checkInitialCommit(const std::string& userDevice, const std::string& commitId, const std::string& commitMsg) const; bool checkValidAdd(const std::string& userDevice, const std::string& uriMember, const std::string& commitid, const std::string& parentId) const; bool checkValidJoins(const std::string& userDevice, const std::string& uriMember, const std::string& commitid, const std::string& parentId) const; bool checkValidRemove(const std::string& userDevice, const std::string& uriMember, const std::string& commitid, const std::string& parentId) const; bool checkValidVoteResolution(const std::string& userDevice, const std::string& uriMember, const std::string& commitId, const std::string& parentId, const std::string& voteType) const; bool checkValidProfileUpdate(const std::string& userDevice, const std::string& commitid, const std::string& parentId) const; bool add(const std::string& path); void addUserDevice(); void resetHard(); // Verify that the device in the repository is still valid bool validateDevice(); std::string commit(const std::string& msg, bool verifyDevice = true); std::string commitMessage(const std::string& msg, bool verifyDevice = true); ConversationMode mode() const; // NOTE! GitDiff needs to be deteleted before repo GitDiff diff(git_repository* repo, const std::string& idNew, const std::string& idOld) const; std::string diffStats(const std::string& newId, const std::string& oldId) const; std::string diffStats(const GitDiff& diff) const; std::vector<ConversationCommit> behind(const std::string& from) const; void forEachCommit(PreConditionCb&& preCondition, std::function<void(ConversationCommit&&)>&& emplaceCb, PostConditionCb&& postCondition, const std::string& from = "", bool logIfNotFound = true) const; std::vector<ConversationCommit> log(const LogOptions& options) const; GitObject fileAtTree(const std::string& path, const GitTree& tree) const; GitObject memberCertificate(std::string_view memberUri, const GitTree& tree) const; // NOTE! GitDiff needs to be deteleted before repo GitTree treeAtCommit(git_repository* repo, const std::string& commitId) const; std::vector<std::string> getInitialMembers() const; bool resolveBan(const std::string_view type, const std::string& uri); bool resolveUnban(const std::string_view type, const std::string& uri); std::weak_ptr<JamiAccount> account_; const std::string id_; const std::string accountId_; const std::string userId_; const std::string deviceId_; mutable std::optional<ConversationMode> mode_ {}; // Members utils mutable std::mutex membersMtx_ {}; std::vector<ConversationMember> members_ {}; std::vector<ConversationMember> members() const { std::lock_guard lk(membersMtx_); return members_; } std::filesystem::path conversationDataPath_ {}; std::filesystem::path membersCache_ {}; std::map<std::string, std::vector<DeviceId>> devices(bool ignoreExpired = true) const { auto acc = account_.lock(); auto repo = repository(); if (!repo or !acc) return {}; std::map<std::string, std::vector<DeviceId>> memberDevices; std::string deviceDir = fmt::format("{}devices/", git_repository_workdir(repo.get())); std::error_code ec; for (const auto& fileIt : std::filesystem::directory_iterator(deviceDir, ec)) { try { auto cert = std::make_shared<dht::crypto::Certificate>( fileutils::loadFile(fileIt.path())); if (!cert) continue; if (ignoreExpired && cert->getExpiration() < std::chrono::system_clock::now()) continue; auto issuerUid = cert->getIssuerUID(); if (!acc->certStore().getCertificate(issuerUid)) { // Check that parentCert auto memberFile = fmt::format("{}members/{}.crt", git_repository_workdir(repo.get()), issuerUid); auto adminFile = fmt::format("{}admins/{}.crt", git_repository_workdir(repo.get()), issuerUid); auto parentCert = std::make_shared<dht::crypto::Certificate>( dhtnet::fileutils::loadFile( std::filesystem::is_regular_file(memberFile, ec) ? memberFile : adminFile)); if (parentCert && (ignoreExpired || parentCert->getExpiration() < std::chrono::system_clock::now())) acc->certStore().pinCertificate( parentCert, true); // Pin certificate to local store if not already done } if (!acc->certStore().getCertificate(cert->getPublicKey().getLongId().toString())) { acc->certStore() .pinCertificate(cert, true); // Pin certificate to local store if not already done } memberDevices[cert->getIssuerUID()].emplace_back(cert->getPublicKey().getLongId()); } catch (const std::exception&) { } } return memberDevices; } std::optional<ConversationCommit> getCommit(const std::string& commitId, bool logIfNotFound = true) const { LogOptions options; options.from = commitId; options.nbOfCommits = 1; options.logIfNotFound = logIfNotFound; auto commits = log(options); if (commits.empty()) return std::nullopt; return std::move(commits[0]); } bool resolveConflicts(git_index* index, const std::string& other_id); std::set<std::string> memberUris(std::string_view filter, const std::set<MemberRole>& filteredRoles) const { std::lock_guard lk(membersMtx_); std::set<std::string> ret; for (const auto& member : members_) { if ((filteredRoles.find(member.role) != filteredRoles.end()) or (not filter.empty() and filter == member.uri)) continue; ret.emplace(member.uri); } return ret; } void initMembers(); std::optional<std::map<std::string, std::string>> convCommitToMap( const ConversationCommit& commit) const; // Permissions MemberRole updateProfilePermLvl_ {MemberRole::ADMIN}; /** * Retrieve the user related to a device using the account's certificate store. * @note deviceToUri_ is used to cache result and avoid always loading the certificate */ std::string uriFromDevice(const std::string& deviceId, const std::string& commitId = "") const { // Check if we have the device in cache. std::lock_guard lk(deviceToUriMtx_); auto it = deviceToUri_.find(deviceId); if (it != deviceToUri_.end()) return it->second; auto acc = account_.lock(); if (!acc) return {}; auto cert = acc->certStore().getCertificate(deviceId); if (!cert || !cert->issuer) { if (!commitId.empty()) { std::string uri = uriFromDeviceAtCommit(deviceId, commitId); if (!uri.empty()) { deviceToUri_.insert({deviceId, uri}); return uri; } } // Not pinned, so load certificate from repo auto repo = repository(); if (!repo) return {}; auto deviceFile = std::filesystem::path(git_repository_workdir(repo.get())) / "devices" / fmt::format("{}.crt", deviceId); if (!std::filesystem::is_regular_file(deviceFile)) return {}; try { cert = std::make_shared<dht::crypto::Certificate>(fileutils::loadFile(deviceFile)); } catch (const std::exception&) { JAMI_WARNING("Unable to load certificate from {}", deviceFile); } if (!cert) return {}; } auto issuerUid = cert->issuer ? cert->issuer->getId().toString() : cert->getIssuerUID(); if (issuerUid.empty()) return {}; deviceToUri_.insert({deviceId, issuerUid}); return issuerUid; } mutable std::mutex deviceToUriMtx_; mutable std::map<std::string, std::string> deviceToUri_; /** * Retrieve the user related to a device using certificate directly from the repository at a * specific commit. * @note Prefer uriFromDevice() if possible as it uses the cache. */ std::string uriFromDeviceAtCommit(const std::string& deviceId, const std::string& commitId) const { auto repo = repository(); if (!repo) return {}; auto tree = treeAtCommit(repo.get(), commitId); auto deviceFile = fmt::format("devices/{}.crt", deviceId); auto blob_device = fileAtTree(deviceFile, tree); if (!blob_device) { JAMI_ERROR("{} announced but not found", deviceId); return {}; } auto deviceCert = dht::crypto::Certificate(as_view(blob_device)); return deviceCert.getIssuerUID(); } /** * Verify that a certificate modification is correct * @param certPath Where the certificate is saved (relative path) * @param userUri Account we want for this certificate * @param oldCert Previous certificate. getId() should return the same id as the new * certificate. * @note There is a few exception because JAMS certificates are buggy right now */ bool verifyCertificate(std::string_view certContent, const std::string& userUri, std::string_view oldCert = ""sv) const { auto cert = dht::crypto::Certificate(certContent); auto isDeviceCertificate = cert.getId().toString() != userUri; auto issuerUid = cert.getIssuerUID(); if (isDeviceCertificate && issuerUid.empty()) { // Err for Jams certificates JAMI_ERROR("Empty issuer for {}", cert.getId().toString()); } if (!oldCert.empty()) { auto deviceCert = dht::crypto::Certificate(oldCert); if (isDeviceCertificate) { if (issuerUid != deviceCert.getIssuerUID()) { // NOTE: Here, because JAMS certificate can be incorrectly formatted, there is // just one valid possibility: passing from an empty issuer to // the valid issuer. if (issuerUid != userUri) { JAMI_ERROR("Device certificate with a bad issuer {}", cert.getId().toString()); return false; } } } else if (cert.getId().toString() != userUri) { JAMI_ERROR("Certificate with a bad Id {}", cert.getId().toString()); return false; } if (cert.getId() != deviceCert.getId()) { JAMI_ERROR("Certificate with a bad Id {}", cert.getId().toString()); return false; } return true; } // If it's a device certificate, we need to verify that the issuer is not modified if (isDeviceCertificate) { // Check that issuer is the one we want. // NOTE: Still one case due to incorrectly formatted certificates from JAMS if (issuerUid != userUri && !issuerUid.empty()) { JAMI_ERROR("Device certificate with a bad issuer {}", cert.getId().toString()); return false; } } else if (cert.getId().toString() != userUri) { JAMI_ERROR("Certificate with a bad Id {}", cert.getId().toString()); return false; } return true; } std::mutex opMtx_; // Mutex for operations }; ///////////////////////////////////////////////////////////////////////////////// /** * Creates an empty repository * @param path Path of the new repository * @return The libgit2's managed repository */ GitRepository create_empty_repository(const std::string& path) { git_repository* repo = nullptr; git_repository_init_options opts; git_repository_init_options_init(&opts, GIT_REPOSITORY_INIT_OPTIONS_VERSION); opts.flags |= GIT_REPOSITORY_INIT_MKPATH; opts.initial_head = "main"; if (git_repository_init_ext(&repo, path.c_str(), &opts) < 0) { JAMI_ERROR("Unable to create a git repository in {}", path); } return {std::move(repo), git_repository_free}; } /** * Add all files to index * @param repo * @return if operation is successful */ bool git_add_all(git_repository* repo) { // git add -A git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo) < 0) { JAMI_ERROR("Unable to open repository index"); return false; } GitIndex index {index_ptr, git_index_free}; git_strarray array {nullptr, 0}; git_index_add_all(index.get(), &array, 0, nullptr, nullptr); git_index_write(index.get()); git_strarray_dispose(&array); return true; } /** * Adds initial files. This adds the certificate of the account in the /admins directory * the device's key in /devices and the CRLs in /CRLs. * @param repo The repository * @return if files were added successfully */ bool add_initial_files(GitRepository& repo, const std::shared_ptr<JamiAccount>& account, ConversationMode mode, const std::string& otherMember = "") { auto deviceId = account->currentDeviceId(); std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto adminsPath = repoPath / "admins"; auto devicesPath = repoPath / "devices"; auto invitedPath = repoPath / "invited"; auto crlsPath = repoPath / "CRLs" / deviceId; if (!dhtnet::fileutils::recursive_mkdir(adminsPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort create conversations", adminsPath); return false; } auto cert = account->identity().second; auto deviceCert = cert->toString(false); auto parentCert = cert->issuer; if (!parentCert) { JAMI_ERROR("Parent cert is null!"); return false; } // /admins auto adminPath = adminsPath / fmt::format("{}.crt", parentCert->getId().toString()); std::ofstream file(adminPath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", adminPath); return false; } file << parentCert->toString(true); file.close(); if (!dhtnet::fileutils::recursive_mkdir(devicesPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort create conversations", devicesPath); return false; } // /devices auto devicePath = devicesPath / fmt::format("{}.crt", deviceId); file = std::ofstream(devicePath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", devicePath); return false; } file << deviceCert; file.close(); if (!dhtnet::fileutils::recursive_mkdir(crlsPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort create conversations", crlsPath); return false; } // /CRLs for (const auto& crl : account->identity().second->getRevocationLists()) { if (!crl) continue; auto crlPath = crlsPath / deviceId / (dht::toHex(crl->getNumber()) + ".crl"); std::ofstream file(crlPath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", crlPath); return false; } file << crl->toString(); file.close(); } // /invited for one to one if (mode == ConversationMode::ONE_TO_ONE) { if (!dhtnet::fileutils::recursive_mkdir(invitedPath, 0700)) { JAMI_ERROR("Error when creating {}.", invitedPath); return false; } auto invitedMemberPath = invitedPath / otherMember; if (std::filesystem::is_regular_file(invitedMemberPath)) { JAMI_WARNING("Member {} already present!", otherMember); return false; } std::ofstream file(invitedMemberPath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", invitedMemberPath); return false; } } if (!git_add_all(repo.get())) { return false; } JAMI_LOG("Initial files added in {}", repoPath); return true; } /** * Sign and create the initial commit * @param repo The git repository * @param account The account who signs * @param mode The mode * @param otherMember If one to one * @return The first commit hash or empty if failed */ std::string initial_commit(GitRepository& repo, const std::shared_ptr<JamiAccount>& account, ConversationMode mode, const std::string& otherMember = "") { auto deviceId = std::string(account->currentDeviceId()); auto name = account->getDisplayName(); if (name.empty()) name = deviceId; name = std::regex_replace(name, regex_display_name, ""); git_signature* sig_ptr = nullptr; git_index* index_ptr = nullptr; git_oid tree_id, commit_id; git_tree* tree_ptr = nullptr; // Sign commit's buffer if (git_signature_new(&sig_ptr, name.c_str(), deviceId.c_str(), std::time(nullptr), 0) < 0) { if (git_signature_new(&sig_ptr, deviceId.c_str(), deviceId.c_str(), std::time(nullptr), 0) < 0) { JAMI_ERROR("Unable to create a commit signature."); return {}; } } GitSignature sig {sig_ptr, git_signature_free}; if (git_repository_index(&index_ptr, repo.get()) < 0) { JAMI_ERROR("Unable to open repository index"); return {}; } GitIndex index {index_ptr, git_index_free}; if (git_index_write_tree(&tree_id, index.get()) < 0) { JAMI_ERROR("Unable to write initial tree from index"); return {}; } if (git_tree_lookup(&tree_ptr, repo.get(), &tree_id) < 0) { JAMI_ERROR("Unable to look up initial tree"); return {}; } GitTree tree = {tree_ptr, git_tree_free}; Json::Value json; json["mode"] = static_cast<int>(mode); if (mode == ConversationMode::ONE_TO_ONE) { json["invited"] = otherMember; } json["type"] = "initial"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; git_buf to_sign = {}; if (git_commit_create_buffer(&to_sign, repo.get(), sig.get(), sig.get(), nullptr, Json::writeString(wbuilder, json).c_str(), tree.get(), 0, nullptr) < 0) { JAMI_ERROR("Unable to create initial buffer"); return {}; } std::string signed_str = base64::encode( account->identity().first->sign((const uint8_t*) to_sign.ptr, to_sign.size)); // git commit -S if (git_commit_create_with_signature(&commit_id, repo.get(), to_sign.ptr, signed_str.c_str(), "signature") < 0) { git_buf_dispose(&to_sign); JAMI_ERROR("Unable to sign initial commit"); return {}; } git_buf_dispose(&to_sign); // Move commit to main branch git_commit* commit = nullptr; if (git_commit_lookup(&commit, repo.get(), &commit_id) == 0) { git_reference* ref = nullptr; git_branch_create(&ref, repo.get(), "main", commit, true); git_commit_free(commit); git_reference_free(ref); } auto commit_str = git_oid_tostr_s(&commit_id); if (commit_str) return commit_str; return {}; } ////////////////////////////////// GitSignature ConversationRepository::Impl::signature() { auto name = getDisplayName(); if (name.empty()) { JAMI_ERROR("[conv {}] Unable to create a commit signature: no name set", id_); return {nullptr, git_signature_free}; } git_signature* sig_ptr = nullptr; // Sign commit's buffer if (git_signature_new(&sig_ptr, name.c_str(), deviceId_.c_str(), std::time(nullptr), 0) < 0) { // Maybe the display name is invalid (like " ") - try without int err = git_signature_new(&sig_ptr, deviceId_.c_str(), deviceId_.c_str(), std::time(nullptr), 0); if (err < 0) { JAMI_ERROR("[conv {}] Unable to create a commit signature: {}", id_, err); return {nullptr, git_signature_free}; } } return {sig_ptr, git_signature_free}; } std::string ConversationRepository::Impl::createMergeCommit(git_index* index, const std::string& wanted_ref) { if (!validateDevice()) { JAMI_ERROR("[conv {}] Invalid device. Not migrated?", id_); return {}; } // The merge will occur between current HEAD and wanted_ref git_reference* head_ref_ptr = nullptr; auto repo = repository(); if (!repo || git_repository_head(&head_ref_ptr, repo.get()) < 0) { JAMI_ERROR("[conv {}] Unable to get HEAD reference", id_); return {}; } GitReference head_ref {head_ref_ptr, git_reference_free}; // Maybe that's a ref, so DWIM it git_reference* merge_ref_ptr = nullptr; git_reference_dwim(&merge_ref_ptr, repo.get(), wanted_ref.c_str()); GitReference merge_ref {merge_ref_ptr, git_reference_free}; GitSignature sig {signature()}; // Prepare a standard merge commit message const char* msg_target = nullptr; if (merge_ref) { git_branch_name(&msg_target, merge_ref.get()); } else { msg_target = wanted_ref.c_str(); } auto commitMsg = fmt::format("Merge {} '{}'", merge_ref ? "branch" : "commit", msg_target); // Setup our parent commits GitCommit parents[2] {{nullptr, git_commit_free}, {nullptr, git_commit_free}}; git_commit* parent = nullptr; if (git_reference_peel((git_object**) &parent, head_ref.get(), GIT_OBJ_COMMIT) < 0) { JAMI_ERROR("[conv {}] Unable to peel HEAD reference", id_); return {}; } parents[0] = {parent, git_commit_free}; git_oid commit_id; if (git_oid_fromstr(&commit_id, wanted_ref.c_str()) < 0) { return {}; } git_annotated_commit* annotated_ptr = nullptr; if (git_annotated_commit_lookup(&annotated_ptr, repo.get(), &commit_id) < 0) { JAMI_ERROR("[conv {}] Unable to lookup commit {}", id_, wanted_ref); return {}; } GitAnnotatedCommit annotated {annotated_ptr, git_annotated_commit_free}; if (git_commit_lookup(&parent, repo.get(), git_annotated_commit_id(annotated.get())) < 0) { JAMI_ERROR("[conv {}] Unable to lookup commit {}", id_, wanted_ref); return {}; } parents[1] = {parent, git_commit_free}; // Prepare our commit tree git_oid tree_oid; git_tree* tree_ptr = nullptr; if (git_index_write_tree_to(&tree_oid, index, repo.get()) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("[conv {}] Unable to write index: {}", id_, err->message); return {}; } if (git_tree_lookup(&tree_ptr, repo.get(), &tree_oid) < 0) { JAMI_ERROR("[conv {}] Unable to lookup tree", id_); return {}; } GitTree tree = {tree_ptr, git_tree_free}; // Commit git_buf to_sign = {}; // Check if the libgit2 library version is 1.8.0 or higher #if( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 8 ) // For libgit2 version 1.8.0 and above git_commit* const parents_ptr[2] {parents[0].get(), parents[1].get()}; #else // For libgit2 versions older than 1.8.0 const git_commit* parents_ptr[2] {parents[0].get(), parents[1].get()}; #endif if (git_commit_create_buffer(&to_sign, repo.get(), sig.get(), sig.get(), nullptr, commitMsg.c_str(), tree.get(), 2, &parents_ptr[0]) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("[conv {}] Unable to create commit buffer: {}", id_, err->message); return {}; } auto account = account_.lock(); if (!account) return {}; // git commit -S auto to_sign_vec = std::vector<uint8_t>(to_sign.ptr, to_sign.ptr + to_sign.size); auto signed_buf = account->identity().first->sign(to_sign_vec); std::string signed_str = base64::encode(signed_buf); git_oid commit_oid; if (git_commit_create_with_signature(&commit_oid, repo.get(), to_sign.ptr, signed_str.c_str(), "signature") < 0) { git_buf_dispose(&to_sign); JAMI_ERROR("[conv {}] Unable to sign commit", id_); return {}; } git_buf_dispose(&to_sign); auto commit_str = git_oid_tostr_s(&commit_oid); if (commit_str) { JAMI_LOG("[conv {}] New merge commit added with id: {}", id_, commit_str); // Move commit to main branch git_reference* ref_ptr = nullptr; if (git_reference_create(&ref_ptr, repo.get(), "refs/heads/main", &commit_oid, true, nullptr) < 0) { const git_error* err = giterr_last(); if (err) { JAMI_ERROR("[conv {}] Unable to move commit to main: {}", id_, err->message); emitSignal<libjami::ConversationSignal::OnConversationError>(accountId_, id_, ECOMMIT, err->message); } return {}; } git_reference_free(ref_ptr); } // We're done merging, cleanup the repository state & index git_repository_state_cleanup(repo.get()); git_object* target_ptr = nullptr; if (git_object_lookup(&target_ptr, repo.get(), &commit_oid, GIT_OBJ_COMMIT) != 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("[conv {}] failed to lookup OID {}: {}", id_, git_oid_tostr_s(&commit_oid), err->message); return {}; } GitObject target {target_ptr, git_object_free}; git_reset(repo.get(), target.get(), GIT_RESET_HARD, nullptr); return commit_str ? commit_str : ""; } bool ConversationRepository::Impl::mergeFastforward(const git_oid* target_oid, int is_unborn) { // Initialize target git_reference* target_ref_ptr = nullptr; auto repo = repository(); if (!repo) { JAMI_ERROR("[conv {}] No repository found", id_); return false; } if (is_unborn) { git_reference* head_ref_ptr = nullptr; // HEAD reference is unborn, lookup manually so we don't try to resolve it if (git_reference_lookup(&head_ref_ptr, repo.get(), "HEAD") < 0) { JAMI_ERROR("[conv {}] failed to lookup HEAD ref", id_); return false; } GitReference head_ref {head_ref_ptr, git_reference_free}; // Grab the reference HEAD should be pointing to const auto* symbolic_ref = git_reference_symbolic_target(head_ref.get()); // Create our main reference on the target OID if (git_reference_create(&target_ref_ptr, repo.get(), symbolic_ref, target_oid, 0, nullptr) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("[conv {}] failed to create main reference: {}", id_, err->message); return false; } } else if (git_repository_head(&target_ref_ptr, repo.get()) < 0) { // HEAD exists, just lookup and resolve JAMI_ERROR("[conv {}] failed to get HEAD reference", id_); return false; } GitReference target_ref {target_ref_ptr, git_reference_free}; // Lookup the target object git_object* target_ptr = nullptr; if (git_object_lookup(&target_ptr, repo.get(), target_oid, GIT_OBJ_COMMIT) != 0) { JAMI_ERROR("[conv {}] failed to lookup OID {}", id_, git_oid_tostr_s(target_oid)); return false; } GitObject target {target_ptr, git_object_free}; // Checkout the result so the workdir is in the expected state git_checkout_options ff_checkout_options; git_checkout_init_options(&ff_checkout_options, GIT_CHECKOUT_OPTIONS_VERSION); ff_checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE; if (git_checkout_tree(repo.get(), target.get(), &ff_checkout_options) != 0) { if (auto err = git_error_last()) JAMI_ERROR("[conv {}] failed to checkout HEAD reference: {}", id_, err->message); else JAMI_ERROR("[conv {}] failed to checkout HEAD reference: unknown error", id_); return false; } // Move the target reference to the target OID git_reference* new_target_ref; if (git_reference_set_target(&new_target_ref, target_ref.get(), target_oid, nullptr) < 0) { JAMI_ERROR("[conv {}] failed to move HEAD reference", id_); return false; } git_reference_free(new_target_ref); return true; } bool ConversationRepository::Impl::add(const std::string& path) { auto repo = repository(); if (!repo) return false; git_index* index_ptr = nullptr; if (git_repository_index(&index_ptr, repo.get()) < 0) { JAMI_ERROR("Unable to open repository index"); return false; } GitIndex index {index_ptr, git_index_free}; if (git_index_add_bypath(index.get(), path.c_str()) != 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("Error when adding file: {}", err->message); return false; } return git_index_write(index.get()) == 0; } bool ConversationRepository::Impl::checkValidUserDiff(const std::string& userDevice, const std::string& commitId, const std::string& parentId) const { // Retrieve tree for recent commit auto repo = repository(); if (!repo) return false; // Here, we check that a file device is modified or not. auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); if (changedFiles.size() == 0) return true; // If a certificate is modified (in the changedFiles), it MUST be a certificate from the user // Retrieve userUri auto treeNew = treeAtCommit(repo.get(), commitId); auto userUri = uriFromDevice(userDevice, commitId); if (userUri.empty()) return false; std::string userDeviceFile = fmt::format("devices/{}.crt", userDevice); std::string adminsFile = fmt::format("admins/{}.crt", userUri); std::string membersFile = fmt::format("members/{}.crt", userUri); auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeNew or not treeOld) return false; for (const auto& changedFile : changedFiles) { if (changedFile == adminsFile || changedFile == membersFile) { // In this case, we should verify it's not added (normal commit, not a member change) // but only updated auto oldFile = fileAtTree(changedFile, treeOld); if (!oldFile) { JAMI_ERROR("Invalid file modified: {}", changedFile); return false; } auto newFile = fileAtTree(changedFile, treeNew); if (!verifyCertificate(as_view(newFile), userUri, as_view(oldFile))) { JAMI_ERROR("Invalid certificate {}", changedFile); return false; } } else if (changedFile == userDeviceFile) { // In this case, device is added or modified (certificate expiration) auto oldFile = fileAtTree(changedFile, treeOld); std::string_view oldCert; if (oldFile) oldCert = as_view(oldFile); auto newFile = fileAtTree(changedFile, treeNew); if (!verifyCertificate(as_view(newFile), userUri, oldCert)) { JAMI_ERROR("Invalid certificate {}", changedFile); return false; } } else { // Invalid file detected JAMI_ERROR("Invalid add file detected: {} {}", changedFile, (int) *mode_); return false; } } return true; } bool ConversationRepository::Impl::checkEdit(const std::string& userDevice, const ConversationCommit& commit) const { auto repo = repository(); if (!repo) return false; auto userUri = uriFromDevice(userDevice, commit.id); if (userUri.empty()) return false; // Check that edited commit is found, for the same author, and editable (plain/text) auto commitMap = convCommitToMap(commit); if (commitMap == std::nullopt) { return false; } auto editedId = commitMap->at("edit"); auto editedCommit = getCommit(editedId); if (editedCommit == std::nullopt) { JAMI_ERROR("Commit {:s} not found", editedId); return false; } auto editedCommitMap = convCommitToMap(*editedCommit); if (editedCommitMap == std::nullopt or editedCommitMap->at("author").empty() or editedCommitMap->at("author") != commitMap->at("author") or commitMap->at("author") != userUri) { JAMI_ERROR("Edited commit {:s} got a different author ({:s})", editedId, commit.id); return false; } if (editedCommitMap->at("type") == "text/plain") { return true; } if (editedCommitMap->at("type") == "application/data-transfer+json") { if (editedCommitMap->find("tid") != editedCommitMap->end()) return true; } JAMI_ERROR("Edited commit {:s} is not valid!", editedId); return false; } bool ConversationRepository::Impl::checkVote(const std::string& userDevice, const std::string& commitId, const std::string& parentId) const { // Check that maximum deviceFile and a vote is added auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); if (changedFiles.size() == 0) { return true; } else if (changedFiles.size() > 2) { return false; } // If modified, it's the first commit of a device, we check // that the file wasn't there previously. And the vote MUST be added std::string deviceFile = ""; std::string votedFile = ""; for (const auto& changedFile : changedFiles) { // NOTE: libgit2 return a diff with /, not DIR_SEPARATOR_DIR if (changedFile == fmt::format("devices/{}.crt", userDevice)) { deviceFile = changedFile; } else if (changedFile.find("votes") == 0) { votedFile = changedFile; } else { // Invalid file detected JAMI_ERROR("Invalid vote file detected: {}", changedFile); return false; } } if (votedFile.empty()) { JAMI_WARNING("No vote detected for commit {}", commitId); return false; } auto repo = repository(); if (!repo) return false; auto treeNew = treeAtCommit(repo.get(), commitId); auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeNew or not treeOld) return false; auto userUri = uriFromDevice(userDevice, commitId); if (userUri.empty()) return false; // Check that voter is admin auto adminFile = fmt::format("admins/{}.crt", userUri); if (!fileAtTree(adminFile, treeOld)) { JAMI_ERROR("Vote from non admin: {}", userUri); return false; } // Check votedFile path static const std::regex regex_votes( "votes.(\\w+).(members|devices|admins|invited).(\\w+).(\\w+)"); std::svmatch base_match; if (!std::regex_match(votedFile, base_match, regex_votes) or base_match.size() != 5) { JAMI_WARNING("Invalid votes path: {}", votedFile); return false; } std::string_view matchedUri = svsub_match_view(base_match[4]); if (matchedUri != userUri) { JAMI_ERROR("Admin voted for other user: {:s} vs {:s}", userUri, matchedUri); return false; } std::string_view votedUri = svsub_match_view(base_match[3]); std::string_view type = svsub_match_view(base_match[2]); std::string_view voteType = svsub_match_view(base_match[1]); if (voteType != "ban" && voteType != "unban") { JAMI_ERROR("Unrecognized vote {:s}", voteType); return false; } // Check that vote file is empty and wasn't modified if (fileAtTree(votedFile, treeOld)) { JAMI_ERROR("Invalid voted file modified: {:s}", votedFile); return false; } auto vote = fileAtTree(votedFile, treeNew); if (!vote) { JAMI_ERROR("No vote file found for: {:s}", userUri); return false; } auto voteContent = as_view(vote); if (!voteContent.empty()) { JAMI_ERROR("Vote file not empty: {:s}", votedFile); return false; } // Check that peer voted is only other device or other member if (type != "devices") { if (votedUri == userUri) { JAMI_ERROR("Detected vote for self: {:s}", votedUri); return false; } if (voteType == "ban") { // file in members or admin or invited auto invitedFile = fmt::format("invited/{}", votedUri); if (!memberCertificate(votedUri, treeOld) && !fileAtTree(invitedFile, treeOld)) { JAMI_ERROR("No member file found for vote: {:s}", votedUri); return false; } } } else { // Check not current device if (votedUri == userDevice) { JAMI_ERROR("Detected vote for self: {:s}", votedUri); return false; } // File in devices deviceFile = fmt::format("devices/{}.crt", votedUri); if (!fileAtTree(deviceFile, treeOld)) { JAMI_ERROR("No device file found for vote: {:s}", votedUri); return false; } } return true; } bool ConversationRepository::Impl::checkValidAdd(const std::string& userDevice, const std::string& uriMember, const std::string& commitId, const std::string& parentId) const { auto repo = repository(); if (not repo) return false; // std::string repoPath = git_repository_workdir(repo.get()); if (mode() == ConversationMode::ONE_TO_ONE) { auto initialMembers = getInitialMembers(); auto it = std::find(initialMembers.begin(), initialMembers.end(), uriMember); if (it == initialMembers.end()) { JAMI_ERROR("Invalid add in one to one conversation: {}", uriMember); return false; } } auto userUri = uriFromDevice(userDevice, commitId); if (userUri.empty()) return false; // Check that only /invited/uri.crt is added & deviceFile & CRLs auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); if (changedFiles.size() == 0) { return false; } else if (changedFiles.size() > 3) { return false; } // Check that user added is not sender if (userUri == uriMember) { JAMI_ERROR("Member tried to add self: {}", userUri); return false; } // If modified, it's the first commit of a device, we check // that the file wasn't there previously. And the member MUST be added // NOTE: libgit2 return a diff with /, not DIR_SEPARATOR_DIR std::string deviceFile = ""; std::string invitedFile = ""; std::string crlFile = std::string("CRLs/") + userUri; for (const auto& changedFile : changedFiles) { if (changedFile == std::string("devices/") + userDevice + ".crt") { deviceFile = changedFile; } else if (changedFile == std::string("invited/") + uriMember) { invitedFile = changedFile; } else if (changedFile == crlFile) { // Nothing to do } else { // Invalid file detected JAMI_ERROR("Invalid add file detected: {}", changedFile); return false; } } auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeOld) return false; auto treeNew = treeAtCommit(repo.get(), commitId); auto blob_invite = fileAtTree(invitedFile, treeNew); if (!blob_invite) { JAMI_ERROR("Invitation not found for commit {}", commitId); return false; } auto invitation = as_view(blob_invite); if (!invitation.empty()) { JAMI_ERROR("Invitation not empty for commit {}", commitId); return false; } // Check that user not in /banned std::string bannedFile = std::string("banned") + "/" + "members" + "/" + uriMember + ".crt"; if (fileAtTree(bannedFile, treeOld)) { JAMI_ERROR("Tried to add banned member: {}", bannedFile); return false; } return true; } bool ConversationRepository::Impl::checkValidJoins(const std::string& userDevice, const std::string& uriMember, const std::string& commitId, const std::string& parentId) const { // Check no other files changed auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); auto invitedFile = fmt::format("invited/{}", uriMember); auto membersFile = fmt::format("members/{}.crt", uriMember); auto deviceFile = fmt::format("devices/{}.crt", userDevice); for (auto& file : changedFiles) { if (file != invitedFile && file != membersFile && file != deviceFile) { JAMI_ERROR("Unwanted file {} found", file); return false; } } // Retrieve tree for commits auto repo = repository(); assert(repo); auto treeNew = treeAtCommit(repo.get(), commitId); auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeNew or not treeOld) return false; // Check /invited if (fileAtTree(invitedFile, treeNew)) { JAMI_ERROR("{} invited not removed", uriMember); return false; } if (!fileAtTree(invitedFile, treeOld)) { JAMI_ERROR("{} invited not found", uriMember); return false; } // Check /members added if (!fileAtTree(membersFile, treeNew)) { JAMI_ERROR("{} members not found", uriMember); return false; } if (fileAtTree(membersFile, treeOld)) { JAMI_ERROR("{} members found too soon", uriMember); return false; } // Check /devices added if (!fileAtTree(deviceFile, treeNew)) { JAMI_ERROR("{} devices not found", uriMember); return false; } // Check certificate auto blob_device = fileAtTree(deviceFile, treeNew); if (!blob_device) { JAMI_ERROR("{} announced but not found", deviceFile); return false; } auto deviceCert = dht::crypto::Certificate(as_view(blob_device)); auto blob_member = fileAtTree(membersFile, treeNew); if (!blob_member) { JAMI_ERROR("{} announced but not found", userDevice); return false; } auto memberCert = dht::crypto::Certificate(as_view(blob_member)); if (memberCert.getId().toString() != deviceCert.getIssuerUID() || deviceCert.getIssuerUID() != uriMember) { JAMI_ERROR("Incorrect device certificate {} for user {}", userDevice, uriMember); return false; } return true; } bool ConversationRepository::Impl::checkValidRemove(const std::string& userDevice, const std::string& uriMember, const std::string& commitId, const std::string& parentId) const { // Retrieve tree for recent commit auto repo = repository(); if (!repo) return false; auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeOld) return false; auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); // NOTE: libgit2 return a diff with /, not DIR_SEPARATOR_DIR std::string deviceFile = fmt::format("devices/{}.crt", userDevice); std::string adminFile = fmt::format("admins/{}.crt", uriMember); std::string memberFile = fmt::format("members/{}.crt", uriMember); std::string crlFile = fmt::format("CRLs/{}", uriMember); std::string invitedFile = fmt::format("invited/{}", uriMember); std::vector<std::string> devicesRemoved; // Check that no weird file is added nor removed static const std::regex regex_devices("devices.(\\w+)\\.crt"); std::smatch base_match; for (const auto& f : changedFiles) { if (f == deviceFile || f == adminFile || f == memberFile || f == crlFile || f == invitedFile) { // Ignore continue; } else if (std::regex_match(f, base_match, regex_devices)) { if (base_match.size() == 2) devicesRemoved.emplace_back(base_match[1]); } else { JAMI_ERROR("Unwanted changed file detected: {}", f); return false; } } // Check that removed devices are for removed member (or directly uriMember) for (const auto& deviceUri : devicesRemoved) { deviceFile = fmt::format("devices/{}.crt", deviceUri); auto blob_device = fileAtTree(deviceFile, treeOld); if (!blob_device) { JAMI_ERROR("device not found added ({})", deviceFile); return false; } auto deviceCert = dht::crypto::Certificate(as_view(blob_device)); auto userUri = deviceCert.getIssuerUID(); if (uriMember != userUri and uriMember != deviceUri /* If device is removed */) { JAMI_ERROR("device removed but not for removed user ({})", deviceFile); return false; } } return true; } bool ConversationRepository::Impl::checkValidVoteResolution(const std::string& userDevice, const std::string& uriMember, const std::string& commitId, const std::string& parentId, const std::string& voteType) const { // Retrieve tree for recent commit auto repo = repository(); if (!repo) return false; auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeOld) return false; auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); // NOTE: libgit2 return a diff with /, not DIR_SEPARATOR_DIR std::string deviceFile = fmt::format("devices/{}.crt", userDevice); std::string adminFile = fmt::format("admins/{}.crt", uriMember); std::string memberFile = fmt::format("members/{}.crt", uriMember); std::string crlFile = fmt::format("CRLs/{}", uriMember); std::string invitedFile = fmt::format("invited/{}", uriMember); std::vector<std::string> voters; std::vector<std::string> devicesRemoved; std::vector<std::string> bannedFiles; // Check that no weird file is added nor removed const std::regex regex_votes("votes." + voteType + ".(members|devices|admins|invited).(\\w+).(\\w+)"); static const std::regex regex_devices("devices.(\\w+)\\.crt"); static const std::regex regex_banned("banned.(members|devices|admins).(\\w+)\\.crt"); static const std::regex regex_banned_invited("banned.(invited).(\\w+)"); std::smatch base_match; for (const auto& f : changedFiles) { if (f == deviceFile || f == adminFile || f == memberFile || f == crlFile || f == invitedFile) { // Ignore continue; } else if (std::regex_match(f, base_match, regex_votes)) { if (base_match.size() != 4 or base_match[2] != uriMember) { JAMI_ERROR("Invalid vote file detected: {}", f); return false; } voters.emplace_back(base_match[3]); // Check that votes were not added here if (!fileAtTree(f, treeOld)) { JAMI_ERROR("invalid vote added ({})", f); return false; } } else if (std::regex_match(f, base_match, regex_devices)) { if (base_match.size() == 2) devicesRemoved.emplace_back(base_match[1]); } else if (std::regex_match(f, base_match, regex_banned) || std::regex_match(f, base_match, regex_banned_invited)) { bannedFiles.emplace_back(f); if (base_match.size() != 3 or base_match[2] != uriMember) { JAMI_ERROR("Invalid banned file detected : {}", f); return false; } } else { JAMI_ERROR("Unwanted changed file detected: {}", f); return false; } } // Check that removed devices are for removed member (or directly uriMember) for (const auto& deviceUri : devicesRemoved) { deviceFile = fmt::format("devices/{}.crt", deviceUri); if (voteType == "ban") { // If we ban a device, it should be there before if (!fileAtTree(deviceFile, treeOld)) { JAMI_ERROR("device not found added ({})", deviceFile); return false; } } else if (voteType == "unban") { // If we unban a device, it should not be there before if (fileAtTree(deviceFile, treeOld)) { JAMI_ERROR("device not found added ({})", deviceFile); return false; } } if (uriMember != uriFromDevice(deviceUri) and uriMember != deviceUri /* If device is removed */) { JAMI_ERROR("device removed but not for removed user ({})", deviceFile); return false; } } auto userUri = uriFromDevice(userDevice, commitId); if (userUri.empty()) return false; // Check that voters are admins adminFile = fmt::format("admins/{}.crt", userUri); if (!fileAtTree(adminFile, treeOld)) { JAMI_ERROR("admin file ({}) not found", adminFile); return false; } // If not for self check that vote is valid and not added auto nbAdmins = 0; auto nbVotes = 0; std::string repoPath = git_repository_workdir(repo.get()); for (const auto& certificate : dhtnet::fileutils::readDirectory(repoPath + "admins")) { if (certificate.find(".crt") == std::string::npos) { JAMI_WARNING("Incorrect file found: {}", certificate); continue; } nbAdmins += 1; auto adminUri = certificate.substr(0, certificate.size() - std::string(".crt").size()); if (std::find(voters.begin(), voters.end(), adminUri) != voters.end()) { nbVotes += 1; } } if (nbAdmins == 0 or (static_cast<double>(nbVotes) / static_cast<double>(nbAdmins)) < .5) { JAMI_ERROR("Incomplete vote detected (commit: {})", commitId); return false; } // If not for self check that member or device certificate is moved to banned/ return !bannedFiles.empty(); } bool ConversationRepository::Impl::checkValidProfileUpdate(const std::string& userDevice, const std::string& commitId, const std::string& parentId) const { // Retrieve tree for recent commit auto repo = repository(); if (!repo) return false; auto treeNew = treeAtCommit(repo.get(), commitId); auto treeOld = treeAtCommit(repo.get(), parentId); if (not treeNew or not treeOld) return false; auto userUri = uriFromDevice(userDevice, commitId); if (userUri.empty()) return false; // Check if profile is changed by an user with correct privilege auto valid = false; if (updateProfilePermLvl_ == MemberRole::ADMIN) { std::string adminFile = fmt::format("admins/{}.crt", userUri); auto adminCert = fileAtTree(adminFile, treeNew); valid |= adminCert != nullptr; } if (updateProfilePermLvl_ >= MemberRole::MEMBER) { std::string memberFile = fmt::format("members/{}.crt", userUri); auto memberCert = fileAtTree(memberFile, treeNew); valid |= memberCert != nullptr; } if (!valid) { JAMI_ERROR("Profile changed from unauthorized user: {} ({})", userDevice, userUri); return false; } auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, parentId)); // Check that no weird file is added nor removed std::string userDeviceFile = fmt::format("devices/{}.crt", userDevice); for (const auto& f : changedFiles) { if (f == "profile.vcf") { // Ignore } else if (f == userDeviceFile) { // In this case, device is added or modified (certificate expiration) auto oldFile = fileAtTree(f, treeOld); std::string_view oldCert; if (oldFile) oldCert = as_view(oldFile); auto newFile = fileAtTree(f, treeNew); if (!verifyCertificate(as_view(newFile), userUri, oldCert)) { JAMI_ERROR("Invalid certificate {}", f); return false; } } else { JAMI_ERROR("Unwanted changed file detected: {}", f); return false; } } return true; } bool ConversationRepository::Impl::isValidUserAtCommit(const std::string& userDevice, const std::string& commitId) const { auto acc = account_.lock(); if (!acc) return false; auto cert = acc->certStore().getCertificate(userDevice); auto hasPinnedCert = cert and cert->issuer; auto repo = repository(); if (not repo) return false; // Retrieve tree for commit auto tree = treeAtCommit(repo.get(), commitId); if (not tree) return false; // Check that /devices/userDevice.crt exists std::string deviceFile = fmt::format("devices/{}.crt", userDevice); auto blob_device = fileAtTree(deviceFile, tree); if (!blob_device) { JAMI_ERROR("{} announced but not found", deviceFile); return false; } auto deviceCert = dht::crypto::Certificate(as_view(blob_device)); auto userUri = deviceCert.getIssuerUID(); if (userUri.empty()) { JAMI_ERROR("{} got no issuer UID", deviceFile); if (not hasPinnedCert) { return false; } else { // HACK: JAMS device's certificate does not contains any issuer // So, getIssuerUID() will be empty here, so there is no way // to get the userURI from this certificate. // Uses pinned certificate if one. userUri = cert->issuer->getId().toString(); } } // Check that /(members|admins)/userUri.crt exists auto blob_parent = memberCertificate(userUri, tree); if (not blob_parent) { JAMI_ERROR("Certificate not found for {}", userUri); return false; } // Check that certificates were still valid auto parentCert = dht::crypto::Certificate(as_view(blob_parent)); git_oid oid; git_commit* commit_ptr = nullptr; if (git_oid_fromstr(&oid, commitId.c_str()) < 0 || git_commit_lookup(&commit_ptr, repo.get(), &oid) < 0) { JAMI_WARNING("Failed to look up commit {}", commitId); return false; } GitCommit commit = {commit_ptr, git_commit_free}; auto commitTime = std::chrono::system_clock::from_time_t(git_commit_time(commit.get())); if (deviceCert.getExpiration() < commitTime) { JAMI_ERROR("Certificate {} expired", deviceCert.getId().toString()); return false; } if (parentCert.getExpiration() < commitTime) { JAMI_ERROR("Certificate {} expired", parentCert.getId().toString()); return false; } auto res = parentCert.getId().toString() == userUri; if (res && not hasPinnedCert) { acc->certStore().pinCertificate(std::move(deviceCert)); acc->certStore().pinCertificate(std::move(parentCert)); } return res; } bool ConversationRepository::Impl::checkInitialCommit(const std::string& userDevice, const std::string& commitId, const std::string& commitMsg) const { auto account = account_.lock(); auto repo = repository(); if (not account or not repo) { JAMI_WARNING("Invalid repository detected"); return false; } auto treeNew = treeAtCommit(repo.get(), commitId); auto userUri = uriFromDevice(userDevice, commitId); if (userUri.empty()) return false; auto changedFiles = ConversationRepository::changedFiles(diffStats(commitId, "")); // NOTE: libgit2 return a diff with /, not DIR_SEPARATOR_DIR try { mode(); } catch (...) { JAMI_ERROR("Invalid mode detected for commit: {}", commitId); return false; } std::string invited = {}; if (mode_ == ConversationMode::ONE_TO_ONE) { std::string err; Json::Value cm; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (reader->parse(commitMsg.data(), commitMsg.data() + commitMsg.size(), &cm, &err)) { invited = cm["invited"].asString(); } else { JAMI_WARNING("{}", err); } } auto hasDevice = false, hasAdmin = false; std::string adminsFile = fmt::format("admins/{}.crt", userUri); std::string deviceFile = fmt::format("devices/{}.crt", userDevice); std::string crlFile = fmt::format("CRLs/{}", userUri); std::string invitedFile = fmt::format("invited/{}", invited); // Check that admin cert is added // Check that device cert is added // Check CRLs added // Check that no other file is added // Check if invited file present for one to one. for (const auto& changedFile : changedFiles) { if (changedFile == adminsFile) { hasAdmin = true; auto newFile = fileAtTree(changedFile, treeNew); if (!verifyCertificate(as_view(newFile), userUri)) { JAMI_ERROR("Invalid certificate found {}", changedFile); return false; } } else if (changedFile == deviceFile) { hasDevice = true; auto newFile = fileAtTree(changedFile, treeNew); if (!verifyCertificate(as_view(newFile), userUri)) { JAMI_ERROR("Invalid certificate found {}", changedFile); return false; } } else if (changedFile == crlFile || changedFile == invitedFile) { // Nothing to do continue; } else { // Invalid file detected JAMI_ERROR("Invalid add file detected: {} {}", changedFile, (int) *mode_); return false; } } return hasDevice && hasAdmin; } bool ConversationRepository::Impl::validateDevice() { auto repo = repository(); auto account = account_.lock(); if (!account || !repo) { JAMI_WARNING("[conv {}] Invalid repository detected", id_); return false; } auto path = fmt::format("devices/{}.crt", deviceId_); std::filesystem::path devicePath = git_repository_workdir(repo.get()); devicePath /= path; if (!std::filesystem::is_regular_file(devicePath)) { JAMI_WARNING("[conv {}] Unable to find file {}", id_, devicePath); return false; } auto wrongDeviceFile = false; try { auto deviceCert = dht::crypto::Certificate(fileutils::loadFile(devicePath)); wrongDeviceFile = !account->isValidAccountDevice(deviceCert); } catch (const std::exception&) { wrongDeviceFile = true; } if (wrongDeviceFile) { JAMI_WARNING("[conv {}] Device certificate is no longer valid. Attempting to update certificate.", id_); // Replace certificate with current cert auto cert = account->identity().second; if (!cert || !account->isValidAccountDevice(*cert)) { JAMI_ERROR("[conv {}] Current device's certificate is invalid. A migration is needed", id_); return false; } std::ofstream file(devicePath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("[conv {}] Unable to write data to {}", id_, devicePath); return false; } file << cert->toString(false); file.close(); if (!add(path)) { JAMI_ERROR("[conv {}] Unable to add file {}", id_, devicePath); return false; } } // Check account cert (a new device can be added but account certifcate can be the old one!) auto adminPath = fmt::format("admins/{}.crt", userId_); auto memberPath = fmt::format("members/{}.crt", userId_); std::filesystem::path parentPath = git_repository_workdir(repo.get()); std::filesystem::path relativeParentPath; if (std::filesystem::is_regular_file(parentPath / adminPath)) relativeParentPath = adminPath; else if (std::filesystem::is_regular_file(parentPath / memberPath)) relativeParentPath = memberPath; parentPath /= relativeParentPath; if (relativeParentPath.empty()) { JAMI_ERROR("[conv {}] Invalid parent path (not in members or admins)", id_); return false; } wrongDeviceFile = false; try { auto parentCert = dht::crypto::Certificate(fileutils::loadFile(parentPath)); wrongDeviceFile = !account->isValidAccountDevice(parentCert); } catch (const std::exception&) { wrongDeviceFile = true; } if (wrongDeviceFile) { JAMI_WARNING("[conv {}] Account certificate is no longer valid. Attempting to update certificate.", id_); auto cert = account->identity().second; auto newCert = cert->issuer; if (newCert && std::filesystem::is_regular_file(parentPath)) { std::ofstream file(parentPath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", path); return false; } file << newCert->toString(true); file.close(); if (!add(relativeParentPath.string())) { JAMI_WARNING("Unable to add file {}", path); return false; } } } return true; } std::string ConversationRepository::Impl::commit(const std::string& msg, bool verifyDevice) { if (verifyDevice && !validateDevice()) { JAMI_ERROR("[conv {}] commit failed: Invalid device", id_); return {}; } GitSignature sig = signature(); if (!sig) { JAMI_ERROR("[conv {}] commit failed: Unable to generate signature", id_); return {}; } auto account = account_.lock(); // Retrieve current index git_index* index_ptr = nullptr; auto repo = repository(); if (!repo) return {}; if (git_repository_index(&index_ptr, repo.get()) < 0) { JAMI_ERROR("[conv {}] commit failed: Unable to open repository index", id_); return {}; } GitIndex index {index_ptr, git_index_free}; git_oid tree_id; if (git_index_write_tree(&tree_id, index.get()) < 0) { JAMI_ERROR("[conv {}] commit failed: Unable to write initial tree from index", id_); return {}; } git_tree* tree_ptr = nullptr; if (git_tree_lookup(&tree_ptr, repo.get(), &tree_id) < 0) { JAMI_ERROR("[conv {}] Unable to look up initial tree", id_); return {}; } GitTree tree = {tree_ptr, git_tree_free}; git_oid commit_id; if (git_reference_name_to_id(&commit_id, repo.get(), "HEAD") < 0) { JAMI_ERROR("[conv {}] Unable to get reference for HEAD", id_); return {}; } git_commit* head_ptr = nullptr; if (git_commit_lookup(&head_ptr, repo.get(), &commit_id) < 0) { JAMI_ERROR("[conv {}] Unable to look up HEAD commit", id_); return {}; } GitCommit head_commit {head_ptr, git_commit_free}; git_buf to_sign = {}; // Check if the libgit2 library version is 1.8.0 or higher #if( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 8 ) // For libgit2 version 1.8.0 and above git_commit* const head_ref[1] = {head_commit.get()}; #else const git_commit* head_ref[1] = {head_commit.get()}; #endif if (git_commit_create_buffer(&to_sign, repo.get(), sig.get(), sig.get(), nullptr, msg.c_str(), tree.get(), 1, &head_ref[0]) < 0) { JAMI_ERROR("[conv {}] Unable to create commit buffer", id_); return {}; } // git commit -S auto to_sign_vec = std::vector<uint8_t>(to_sign.ptr, to_sign.ptr + to_sign.size); auto signed_buf = account->identity().first->sign(to_sign_vec); std::string signed_str = base64::encode(signed_buf); if (git_commit_create_with_signature(&commit_id, repo.get(), to_sign.ptr, signed_str.c_str(), "signature") < 0) { JAMI_ERROR("[conv {}] Unable to sign commit", id_); git_buf_dispose(&to_sign); return {}; } git_buf_dispose(&to_sign); // Move commit to main branch git_reference* ref_ptr = nullptr; if (git_reference_create(&ref_ptr, repo.get(), "refs/heads/main", &commit_id, true, nullptr) < 0) { const git_error* err = giterr_last(); if (err) { JAMI_ERROR("[conv {}] Unable to move commit to main: {}", id_, err->message); emitSignal<libjami::ConversationSignal::OnConversationError>(accountId_, id_, ECOMMIT, err->message); } return {}; } git_reference_free(ref_ptr); auto commit_str = git_oid_tostr_s(&commit_id); if (commit_str) { JAMI_LOG("[conv {}] New message added with id: {}", id_, commit_str); } return commit_str ? commit_str : ""; } ConversationMode ConversationRepository::Impl::mode() const { // If already retrieven, return it, else get it from first commit if (mode_ != std::nullopt) return *mode_; LogOptions options; options.from = id_; options.nbOfCommits = 1; auto lastMsg = log(options); if (lastMsg.size() == 0) { emitSignal<libjami::ConversationSignal::OnConversationError>(accountId_, id_, EINVALIDMODE, "No initial commit"); throw std::logic_error("Unable to retrieve first commit"); } auto commitMsg = lastMsg[0].commit_msg; std::string err; Json::Value root; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(commitMsg.data(), commitMsg.data() + commitMsg.size(), &root, &err)) { emitSignal<libjami::ConversationSignal::OnConversationError>(accountId_, id_, EINVALIDMODE, "No initial commit"); throw std::logic_error("Unable to retrieve first commit"); } if (!root.isMember("mode")) { emitSignal<libjami::ConversationSignal::OnConversationError>(accountId_, id_, EINVALIDMODE, "No mode detected"); throw std::logic_error("No mode detected for initial commit"); } int mode = root["mode"].asInt(); switch (mode) { case 0: mode_ = ConversationMode::ONE_TO_ONE; break; case 1: mode_ = ConversationMode::ADMIN_INVITES_ONLY; break; case 2: mode_ = ConversationMode::INVITES_ONLY; break; case 3: mode_ = ConversationMode::PUBLIC; break; default: emitSignal<libjami::ConversationSignal::OnConversationError>(accountId_, id_, EINVALIDMODE, "Incorrect mode detected"); throw std::logic_error("Incorrect mode detected"); } return *mode_; } std::string ConversationRepository::Impl::diffStats(const std::string& newId, const std::string& oldId) const { if (auto repo = repository()) { if (auto d = diff(repo.get(), newId, oldId)) return diffStats(d); } return {}; } GitDiff ConversationRepository::Impl::diff(git_repository* repo, const std::string& idNew, const std::string& idOld) const { if (!repo) { JAMI_ERROR("Unable to get reference for HEAD"); return {nullptr, git_diff_free}; } // Retrieve tree for commit new git_oid oid; git_commit* commitNew = nullptr; if (idNew == "HEAD") { if (git_reference_name_to_id(&oid, repo, "HEAD") < 0) { JAMI_ERROR("Unable to get reference for HEAD"); return {nullptr, git_diff_free}; } if (git_commit_lookup(&commitNew, repo, &oid) < 0) { JAMI_ERROR("Unable to look up HEAD commit"); return {nullptr, git_diff_free}; } } else { if (git_oid_fromstr(&oid, idNew.c_str()) < 0 || git_commit_lookup(&commitNew, repo, &oid) < 0) { GitCommit new_commit = {commitNew, git_commit_free}; JAMI_WARNING("Failed to look up commit {}", idNew); return {nullptr, git_diff_free}; } } GitCommit new_commit = {commitNew, git_commit_free}; git_tree* tNew = nullptr; if (git_commit_tree(&tNew, new_commit.get()) < 0) { JAMI_ERROR("Unable to look up initial tree"); return {nullptr, git_diff_free}; } GitTree treeNew = {tNew, git_tree_free}; git_diff* diff_ptr = nullptr; if (idOld.empty()) { if (git_diff_tree_to_tree(&diff_ptr, repo, nullptr, treeNew.get(), {}) < 0) { JAMI_ERROR("Unable to get diff to empty repository"); return {nullptr, git_diff_free}; } return {diff_ptr, git_diff_free}; } // Retrieve tree for commit old git_commit* commitOld = nullptr; if (git_oid_fromstr(&oid, idOld.c_str()) < 0 || git_commit_lookup(&commitOld, repo, &oid) < 0) { JAMI_WARNING("Failed to look up commit {}", idOld); return {nullptr, git_diff_free}; } GitCommit old_commit {commitOld, git_commit_free}; git_tree* tOld = nullptr; if (git_commit_tree(&tOld, old_commit.get()) < 0) { JAMI_ERROR("Unable to look up initial tree"); return {nullptr, git_diff_free}; } GitTree treeOld = {tOld, git_tree_free}; // Calc diff if (git_diff_tree_to_tree(&diff_ptr, repo, treeOld.get(), treeNew.get(), {}) < 0) { JAMI_ERROR("Unable to get diff between {} and {}", idOld, idNew); return {nullptr, git_diff_free}; } return {diff_ptr, git_diff_free}; } std::vector<ConversationCommit> ConversationRepository::Impl::behind(const std::string& from) const { git_oid oid_local, oid_head, oid_remote; auto repo = repository(); if (!repo) return {}; if (git_reference_name_to_id(&oid_local, repo.get(), "HEAD") < 0) { JAMI_ERROR("Unable to get reference for HEAD"); return {}; } oid_head = oid_local; std::string head = git_oid_tostr_s(&oid_head); if (git_oid_fromstr(&oid_remote, from.c_str()) < 0) { JAMI_ERROR("Unable to get reference for commit {}", from); return {}; } git_oidarray bases; if (git_merge_bases(&bases, repo.get(), &oid_local, &oid_remote) != 0) { JAMI_ERROR("Unable to get any merge base for commit {} and {}", from, head); return {}; } for (std::size_t i = 0; i < bases.count; ++i) { std::string oid = git_oid_tostr_s(&bases.ids[i]); if (oid != head) { oid_local = bases.ids[i]; break; } } git_oidarray_free(&bases); std::string to = git_oid_tostr_s(&oid_local); if (to == from) return {}; return log(LogOptions {from, to}); } void ConversationRepository::Impl::forEachCommit(PreConditionCb&& preCondition, std::function<void(ConversationCommit&&)>&& emplaceCb, PostConditionCb&& postCondition, const std::string& from, bool logIfNotFound) const { git_oid oid, oidFrom, oidMerge; // Note: Start from head to get all merge possibilities and correct linearized parent. auto repo = repository(); if (!repo or git_reference_name_to_id(&oid, repo.get(), "HEAD") < 0) { JAMI_ERROR("[conv {}] Unable to get reference for HEAD", id_); return; } if (from != "" && git_oid_fromstr(&oidFrom, from.c_str()) == 0) { auto isMergeBase = git_merge_base(&oidMerge, repo.get(), &oid, &oidFrom) == 0 && git_oid_equal(&oidMerge, &oidFrom); if (!isMergeBase) { // We're logging a non merged branch, so, take this one instead of HEAD oid = oidFrom; } } git_revwalk* walker_ptr = nullptr; if (git_revwalk_new(&walker_ptr, repo.get()) < 0 || git_revwalk_push(walker_ptr, &oid) < 0) { GitRevWalker walker {walker_ptr, git_revwalk_free}; // This fail can be ok in the case we check if a commit exists before pulling (so can fail // there). only log if the fail is unwanted. if (logIfNotFound) JAMI_DEBUG("[conv {}] Unable to init revwalker", id_); return; } GitRevWalker walker {walker_ptr, git_revwalk_free}; git_revwalk_sorting(walker.get(), GIT_SORT_TOPOLOGICAL | GIT_SORT_TIME); for (auto idx = 0u; !git_revwalk_next(&oid, walker.get()); ++idx) { git_commit* commit_ptr = nullptr; std::string id = git_oid_tostr_s(&oid); if (git_commit_lookup(&commit_ptr, repo.get(), &oid) < 0) { JAMI_WARNING("[conv {}] Failed to look up commit {}", id_, id); break; } GitCommit commit {commit_ptr, git_commit_free}; const git_signature* sig = git_commit_author(commit.get()); GitAuthor author; author.name = sig->name; author.email = sig->email; std::vector<std::string> parents; auto parentsCount = git_commit_parentcount(commit.get()); for (unsigned int p = 0; p < parentsCount; ++p) { std::string parent {}; const git_oid* pid = git_commit_parent_id(commit.get(), p); if (pid) { parent = git_oid_tostr_s(pid); parents.emplace_back(parent); } } auto result = preCondition(id, author, commit); if (result == CallbackResult::Skip) continue; else if (result == CallbackResult::Break) break; ConversationCommit cc; cc.id = id; cc.commit_msg = git_commit_message(commit.get()); cc.author = std::move(author); cc.parents = std::move(parents); git_buf signature = {}, signed_data = {}; if (git_commit_extract_signature(&signature, &signed_data, repo.get(), &oid, "signature") < 0) { JAMI_WARNING("[conv {}] Unable to extract signature for commit {}", id_, id); } else { cc.signature = base64::decode( std::string(signature.ptr, signature.ptr + signature.size)); cc.signed_content = std::vector<uint8_t>(signed_data.ptr, signed_data.ptr + signed_data.size); } git_buf_dispose(&signature); git_buf_dispose(&signed_data); cc.timestamp = git_commit_time(commit.get()); auto post = postCondition(id, author, cc); emplaceCb(std::move(cc)); if (post) break; } } std::vector<ConversationCommit> ConversationRepository::Impl::log(const LogOptions& options) const { std::vector<ConversationCommit> commits {}; auto startLogging = options.from == ""; auto breakLogging = false; forEachCommit( [&](const auto& id, const auto& author, const auto& commit) { if (!commits.empty()) { // Set linearized parent commits.rbegin()->linearized_parent = id; } if (options.skipMerge && git_commit_parentcount(commit.get()) > 1) { return CallbackResult::Skip; } if ((options.nbOfCommits != 0 && commits.size() == options.nbOfCommits)) return CallbackResult::Break; // Stop logging if (breakLogging) return CallbackResult::Break; // Stop logging if (id == options.to) { if (options.includeTo) breakLogging = true; // For the next commit else return CallbackResult::Break; // Stop logging } if (!startLogging && options.from != "" && options.from == id) startLogging = true; if (!startLogging) return CallbackResult::Skip; // Start logging after this one if (options.fastLog) { if (options.authorUri != "") { if (options.authorUri == uriFromDevice(author.email)) { return CallbackResult::Break; // Found author, stop } } // Used to only count commit commits.emplace(commits.end(), ConversationCommit {}); return CallbackResult::Skip; } return CallbackResult::Ok; // Continue }, [&](auto&& cc) { commits.emplace(commits.end(), std::forward<decltype(cc)>(cc)); }, [](auto, auto, auto) { return false; }, options.from, options.logIfNotFound); return commits; } GitObject ConversationRepository::Impl::fileAtTree(const std::string& path, const GitTree& tree) const { git_object* blob_ptr = nullptr; if (git_object_lookup_bypath(&blob_ptr, reinterpret_cast<git_object*>(tree.get()), path.c_str(), GIT_OBJECT_BLOB) != 0) { return GitObject {nullptr, git_object_free}; } return GitObject {blob_ptr, git_object_free}; } GitObject ConversationRepository::Impl::memberCertificate(std::string_view memberUri, const GitTree& tree) const { auto blob = fileAtTree(fmt::format("members/{}.crt", memberUri), tree); if (not blob) blob = fileAtTree(fmt::format("admins/{}.crt", memberUri), tree); return blob; } GitTree ConversationRepository::Impl::treeAtCommit(git_repository* repo, const std::string& commitId) const { git_oid oid; git_commit* commit = nullptr; if (git_oid_fromstr(&oid, commitId.c_str()) < 0 || git_commit_lookup(&commit, repo, &oid) < 0) { JAMI_WARNING("[conv {}] Failed to look up commit {}", id_, commitId); return GitTree {nullptr, git_tree_free}; } GitCommit gc = {commit, git_commit_free}; git_tree* tree = nullptr; if (git_commit_tree(&tree, gc.get()) < 0) { JAMI_ERROR("[conv {}] Unable to look up initial tree", id_); return GitTree {nullptr, git_tree_free}; } return GitTree {tree, git_tree_free}; } std::vector<std::string> ConversationRepository::Impl::getInitialMembers() const { auto acc = account_.lock(); if (!acc) return {}; LogOptions options; options.from = id_; options.nbOfCommits = 1; auto firstCommit = log(options); if (firstCommit.size() == 0) { return {}; } auto commit = firstCommit[0]; auto authorDevice = commit.author.email; auto cert = acc->certStore().getCertificate(authorDevice); if (!cert || !cert->issuer) return {}; auto authorId = cert->issuer->getId().toString(); if (mode() == ConversationMode::ONE_TO_ONE) { std::string err; Json::Value root; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(commit.commit_msg.data(), commit.commit_msg.data() + commit.commit_msg.size(), &root, &err)) { return {authorId}; } if (root.isMember("invited") && root["invited"].asString() != authorId) return {authorId, root["invited"].asString()}; } return {authorId}; } bool ConversationRepository::Impl::resolveConflicts(git_index* index, const std::string& other_id) { git_index_conflict_iterator* conflict_iterator = nullptr; const git_index_entry* ancestor_out = nullptr; const git_index_entry* our_out = nullptr; const git_index_entry* their_out = nullptr; git_index_conflict_iterator_new(&conflict_iterator, index); GitIndexConflictIterator ci {conflict_iterator, git_index_conflict_iterator_free}; git_oid head_commit_id; auto repo = repository(); if (!repo || git_reference_name_to_id(&head_commit_id, repo.get(), "HEAD") < 0) { JAMI_ERROR("[conv {}] Unable to get reference for HEAD", id_); return false; } auto commit_str = git_oid_tostr_s(&head_commit_id); if (!commit_str) return false; auto useRemote = (other_id > commit_str); // Choose by commit version // NOTE: for now, only authorize conflicts on "profile.vcf" std::vector<git_index_entry> new_entries; while (git_index_conflict_next(&ancestor_out, &our_out, &their_out, ci.get()) != GIT_ITEROVER) { if (ancestor_out && ancestor_out->path && our_out && our_out->path && their_out && their_out->path) { if (std::string(ancestor_out->path) == "profile.vcf") { // Checkout wanted version. copy the index_entry git_index_entry resolution = useRemote ? *their_out : *our_out; resolution.flags &= GIT_INDEX_STAGE_NORMAL; if (!(resolution.flags & GIT_IDXENTRY_VALID)) resolution.flags |= GIT_IDXENTRY_VALID; // NOTE: do no git_index_add yet, wait for after full conflict checks new_entries.push_back(resolution); continue; } JAMI_ERROR("Conflict detected on a file that is not authorized: {}", ancestor_out->path); return false; } return false; } for (auto& entry : new_entries) git_index_add(index, &entry); git_index_conflict_cleanup(index); // Checkout and cleanup git_checkout_options opt; git_checkout_options_init(&opt, GIT_CHECKOUT_OPTIONS_VERSION); opt.checkout_strategy |= GIT_CHECKOUT_FORCE; opt.checkout_strategy |= GIT_CHECKOUT_ALLOW_CONFLICTS; if (other_id > commit_str) opt.checkout_strategy |= GIT_CHECKOUT_USE_THEIRS; else opt.checkout_strategy |= GIT_CHECKOUT_USE_OURS; if (git_checkout_index(repo.get(), index, &opt) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("Unable to checkout index: {}", err->message); return false; } return true; } void ConversationRepository::Impl::initMembers() { auto repo = repository(); if (!repo) throw std::logic_error("Invalid git repository"); std::vector<std::string> uris; std::lock_guard lk(membersMtx_); members_.clear(); std::filesystem::path repoPath = git_repository_workdir(repo.get()); std::vector<std::filesystem::path> paths = {repoPath / "admins", repoPath / "members", repoPath / "invited", repoPath / "banned" / "members", repoPath / "banned" / "invited"}; std::vector<MemberRole> roles = { MemberRole::ADMIN, MemberRole::MEMBER, MemberRole::INVITED, MemberRole::BANNED, MemberRole::BANNED, }; auto i = 0; for (const auto& p : paths) { for (const auto& f : dhtnet::fileutils::readDirectory(p)) { auto pos = f.find(".crt"); auto uri = f.substr(0, pos); auto it = std::find(uris.begin(), uris.end(), uri); if (it == uris.end()) { members_.emplace_back(ConversationMember {uri, roles[i]}); uris.emplace_back(uri); } } ++i; } if (mode() == ConversationMode::ONE_TO_ONE) { for (const auto& member : getInitialMembers()) { auto it = std::find(uris.begin(), uris.end(), member); if (it == uris.end()) { // If member is in initial commit, but not in invited, this means that user left. members_.emplace_back(ConversationMember {member, MemberRole::LEFT}); } } } saveMembers(); } std::optional<std::map<std::string, std::string>> ConversationRepository::Impl::convCommitToMap(const ConversationCommit& commit) const { auto authorId = uriFromDevice(commit.author.email, commit.id); if (authorId.empty()) { JAMI_ERROR("[conv {}] Invalid author id for commit {}", id_, commit.id); return std::nullopt; } std::string parents; auto parentsSize = commit.parents.size(); for (std::size_t i = 0; i < parentsSize; ++i) { parents += commit.parents[i]; if (i != parentsSize - 1) parents += ","; } std::string type {}; if (parentsSize > 1) type = "merge"; std::string body {}; std::map<std::string, std::string> message; if (type.empty()) { std::string err; Json::Value cm; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (reader->parse(commit.commit_msg.data(), commit.commit_msg.data() + commit.commit_msg.size(), &cm, &err)) { for (auto const& id : cm.getMemberNames()) { if (id == "type") { type = cm[id].asString(); continue; } message.insert({id, cm[id].asString()}); } } else { JAMI_WARNING("{}", err); } } if (type.empty()) { return std::nullopt; } else if (type == "application/data-transfer+json") { // Avoid the client to do the concatenation auto tid = message["tid"]; if (not tid.empty()) { auto extension = fileutils::getFileExtension(message["displayName"]); if (!extension.empty()) message["fileId"] = fmt::format("{}_{}.{}", commit.id, tid, extension); else message["fileId"] = fmt::format("{}_{}", commit.id, tid); } else { message["fileId"] = ""; } } message["id"] = commit.id; message["parents"] = parents; message["linearizedParent"] = commit.linearized_parent; message["author"] = authorId; message["type"] = type; message["timestamp"] = std::to_string(commit.timestamp); return message; } std::string ConversationRepository::Impl::diffStats(const GitDiff& diff) const { git_diff_stats* stats_ptr = nullptr; if (git_diff_get_stats(&stats_ptr, diff.get()) < 0) { JAMI_ERROR("[conv {}] Unable to get diff stats", id_); return {}; } GitDiffStats stats = {stats_ptr, git_diff_stats_free}; git_diff_stats_format_t format = GIT_DIFF_STATS_FULL; git_buf statsBuf = {}; if (git_diff_stats_to_buf(&statsBuf, stats.get(), format, 80) < 0) { JAMI_ERROR("[conv {}] Unable to format diff stats", id_); return {}; } auto res = std::string(statsBuf.ptr, statsBuf.ptr + statsBuf.size); git_buf_dispose(&statsBuf); return res; } ////////////////////////////////// std::unique_ptr<ConversationRepository> ConversationRepository::createConversation(const std::shared_ptr<JamiAccount>& account, ConversationMode mode, const std::string& otherMember) { // Create temporary directory because we are unable to know the first hash for now std::uniform_int_distribution<uint64_t> dist; auto conversationsPath = fileutils::get_data_dir() / account->getAccountID() / "conversations"; dhtnet::fileutils::check_dir(conversationsPath); auto tmpPath = conversationsPath / std::to_string(dist(account->rand)); if (std::filesystem::is_directory(tmpPath)) { JAMI_ERROR("{} already exists. Abort create conversations", tmpPath); return {}; } if (!dhtnet::fileutils::recursive_mkdir(tmpPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort create conversations", tmpPath); return {}; } auto repo = create_empty_repository(tmpPath.string()); if (!repo) { return {}; } // Add initial files if (!add_initial_files(repo, account, mode, otherMember)) { JAMI_ERROR("Error when adding initial files"); dhtnet::fileutils::removeAll(tmpPath, true); return {}; } // Commit changes auto id = initial_commit(repo, account, mode, otherMember); if (id.empty()) { JAMI_ERROR("Unable to create initial commit in {}", tmpPath); dhtnet::fileutils::removeAll(tmpPath, true); return {}; } // Move to wanted directory auto newPath = conversationsPath / id; std::error_code ec; std::filesystem::rename(tmpPath, newPath, ec); if (ec) { JAMI_ERROR("Unable to move {} in {}: {}", tmpPath, newPath, ec.message()); dhtnet::fileutils::removeAll(tmpPath, true); return {}; } JAMI_LOG("New conversation initialized in {}", newPath); return std::make_unique<ConversationRepository>(account, id); } std::unique_ptr<ConversationRepository> ConversationRepository::cloneConversation( const std::shared_ptr<JamiAccount>& account, const std::string& deviceId, const std::string& conversationId, std::function<void(std::vector<ConversationCommit>)>&& checkCommitCb) { auto conversationsPath = fileutils::get_data_dir() / account->getAccountID() / "conversations"; dhtnet::fileutils::check_dir(conversationsPath); auto path = conversationsPath / conversationId; auto url = fmt::format("git://{}/{}", deviceId, conversationId); git_clone_options clone_options; git_clone_options_init(&clone_options, GIT_CLONE_OPTIONS_VERSION); git_fetch_options_init(&clone_options.fetch_opts, GIT_FETCH_OPTIONS_VERSION); clone_options.fetch_opts.callbacks.transfer_progress = [](const git_indexer_progress* stats, void*) { // Uncomment to get advancment // if (stats->received_objects % 500 == 0 || stats->received_objects == stats->total_objects) // JAMI_DEBUG("{}/{} {}kb", stats->received_objects, stats->total_objects, // stats->received_bytes/1024); // If a pack is more than 256Mb, it's anormal. if (stats->received_bytes > MAX_FETCH_SIZE) { JAMI_ERROR("Abort fetching repository, the fetch is too big: {} bytes ({}/{})", stats->received_bytes, stats->received_objects, stats->total_objects); return -1; } return 0; }; if (std::filesystem::is_directory(path)) { // If a crash occurs during a previous clone, just in case JAMI_WARNING("Removing existing directory {} (the dir exists and non empty)", path); if (dhtnet::fileutils::removeAll(path, true) != 0) return nullptr; } JAMI_DEBUG("[conv {}] Start clone of {:s} to {}", conversationId, url, path); git_repository* rep = nullptr; git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.fetch_opts.follow_redirects = GIT_REMOTE_REDIRECT_NONE; if (auto err = git_clone(&rep, url.c_str(), path.string().c_str(), &opts)) { if (const git_error* gerr = giterr_last()) JAMI_ERROR("[conv {}] Error when retrieving remote conversation: {:s} {}", conversationId, gerr->message, path); else JAMI_ERROR("[conv {}] Unknown error {:d} when retrieving remote conversation", conversationId, err); return nullptr; } git_repository_free(rep); auto repo = std::make_unique<ConversationRepository>(account, conversationId); repo->pinCertificates(true); // need to load certificates to validate non known members if (!repo->validClone(std::move(checkCommitCb))) { repo->erase(); JAMI_ERROR("[conv {}] error when validating remote conversation", conversationId); return nullptr; } JAMI_LOG("[conv {}] New conversation cloned in {}", conversationId, path); return repo; } bool ConversationRepository::Impl::validCommits( const std::vector<ConversationCommit>& commitsToValidate) const { for (const auto& commit : commitsToValidate) { auto userDevice = commit.author.email; auto validUserAtCommit = commit.id; if (commit.parents.size() == 0) { if (!checkInitialCommit(userDevice, commit.id, commit.commit_msg)) { JAMI_WARNING("[conv {}] Malformed initial commit {}. Please check you use the latest " "version of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed initial commit"); return false; } } else if (commit.parents.size() == 1) { std::string type = {}, editId = {}; std::string err; Json::Value cm; Json::CharReaderBuilder rbuilder; auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (reader->parse(commit.commit_msg.data(), commit.commit_msg.data() + commit.commit_msg.size(), &cm, &err)) { type = cm["type"].asString(); editId = cm["edit"].asString(); } else { JAMI_WARNING("{}", err); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed commit"); return false; } if (type == "vote") { // Check that vote is valid if (!checkVote(userDevice, commit.id, commit.parents[0])) { JAMI_WARNING( "[conv {}] Malformed vote commit {}. Please check you use the latest version " "of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id.c_str()); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed vote"); return false; } } else if (type == "member") { std::string action = cm["action"].asString(); std::string uriMember = cm["uri"].asString(); if (action == "add") { if (!checkValidAdd(userDevice, uriMember, commit.id, commit.parents[0])) { JAMI_WARNING( "[conv {}] Malformed add commit {}. Please check you use the latest version " "of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed add member commit"); return false; } } else if (action == "join") { if (!checkValidJoins(userDevice, uriMember, commit.id, commit.parents[0])) { JAMI_WARNING( "[conv {}] Malformed joins commit {}. Please check you use the latest version " "of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed join member commit"); return false; } } else if (action == "remove") { // In this case, we remove the user. So if self, the user will not be // valid for this commit. Check previous commit validUserAtCommit = commit.parents[0]; if (!checkValidRemove(userDevice, uriMember, commit.id, commit.parents[0])) { JAMI_WARNING( "[conv {}] Malformed removes commit {}. Please check you use the latest version " "of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed remove member commit"); return false; } } else if (action == "ban" || action == "unban") { // Note device.size() == "member".size() if (!checkValidVoteResolution(userDevice, uriMember, commit.id, commit.parents[0], action)) { JAMI_WARNING( "[conv {}] Malformed removes commit {}. Please check you use the latest version " "of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed ban member commit"); return false; } } else { JAMI_WARNING( "[conv {}] Malformed member commit {} with action {}. Please check you use the " "latest " "version of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id, action); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed member commit"); return false; } } else if (type == "application/update-profile") { if (!checkValidProfileUpdate(userDevice, commit.id, commit.parents[0])) { JAMI_WARNING("[conv {}] Malformed profile updates commit {}. Please check you use the " "latest version " "of Jami, or that your contact is not doing unwanted stuff.", id_, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed profile updates commit"); return false; } } else if (type == "application/edited-message" || !editId.empty()) { if (!checkEdit(userDevice, commit)) { JAMI_ERROR("Commit {:s} malformed", commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed edit commit"); return false; } } else { // Note: accept all mimetype here, as we can have new mimetypes // Just avoid to add weird files // Check that no weird file is added outside device cert nor removed if (!checkValidUserDiff(userDevice, commit.id, commit.parents[0])) { JAMI_WARNING( "[conv {}] Malformed {} commit {}. Please check you use the latest " "version of Jami, or that your contact is not doing unwanted stuff.", id_, type, commit.id); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed commit"); return false; } } // For all commit, check that user is valid, // So that user certificate MUST be in /members or /admins // and device cert MUST be in /devices if (!isValidUserAtCommit(userDevice, validUserAtCommit)) { JAMI_WARNING( "[conv {}] Malformed commit {}. Please check you use the latest version of Jami, or " "that your contact is not doing unwanted stuff. {}", id_, validUserAtCommit, commit.commit_msg); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed commit"); return false; } } else { // Merge commit, for now, check user if (!isValidUserAtCommit(userDevice, validUserAtCommit)) { JAMI_WARNING( "[conv {}] Malformed merge commit {}. Please check you use the latest version of " "Jami, or that your contact is not doing unwanted stuff.", id_, validUserAtCommit); emitSignal<libjami::ConversationSignal::OnConversationError>( accountId_, id_, EVALIDFETCH, "Malformed commit"); return false; } } JAMI_DEBUG("[conv {}] Validate commit {}", id_, commit.id); } return true; } ///////////////////////////////////////////////////////////////////////////////// ConversationRepository::ConversationRepository(const std::shared_ptr<JamiAccount>& account, const std::string& id) : pimpl_ {new Impl {account, id}} {} ConversationRepository::~ConversationRepository() = default; const std::string& ConversationRepository::id() const { return pimpl_->id_; } std::string ConversationRepository::addMember(const std::string& uri) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); auto repo = pimpl_->repository(); if (not repo) return {}; // First, we need to add the member file to the repository if not present std::filesystem::path repoPath = git_repository_workdir(repo.get()); std::filesystem::path invitedPath = repoPath / "invited"; if (!dhtnet::fileutils::recursive_mkdir(invitedPath, 0700)) { JAMI_ERROR("Error when creating {}.", invitedPath); return {}; } std::filesystem::path devicePath = invitedPath / uri; if (std::filesystem::is_regular_file(devicePath)) { JAMI_WARNING("Member {} already present!", uri); return {}; } std::ofstream file(devicePath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", devicePath); return {}; } std::string path = "invited/" + uri; if (!pimpl_->add(path)) return {}; { std::lock_guard lk(pimpl_->membersMtx_); pimpl_->members_.emplace_back(ConversationMember {uri, MemberRole::INVITED}); pimpl_->saveMembers(); } Json::Value json; json["action"] = "add"; json["uri"] = uri; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return pimpl_->commit(Json::writeString(wbuilder, json)); } void ConversationRepository::onMembersChanged(OnMembersChanged&& cb) { pimpl_->onMembersChanged_ = std::move(cb); } std::string ConversationRepository::amend(const std::string& id, const std::string& msg) { GitSignature sig = pimpl_->signature(); if (!sig) return {}; git_oid tree_id, commit_id; git_commit* commit_ptr = nullptr; auto repo = pimpl_->repository(); if (!repo || git_oid_fromstr(&tree_id, id.c_str()) < 0 || git_commit_lookup(&commit_ptr, repo.get(), &tree_id) < 0) { GitCommit commit {commit_ptr, git_commit_free}; JAMI_WARNING("Failed to look up commit {}", id); return {}; } GitCommit commit {commit_ptr, git_commit_free}; if (git_commit_amend( &commit_id, commit.get(), nullptr, sig.get(), sig.get(), nullptr, msg.c_str(), nullptr) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("Unable to amend commit: {}", err->message); return {}; } // Move commit to main branch git_reference* ref_ptr = nullptr; if (git_reference_create(&ref_ptr, repo.get(), "refs/heads/main", &commit_id, true, nullptr) < 0) { const git_error* err = giterr_last(); if (err) { JAMI_ERROR("Unable to move commit to main: {}", err->message); emitSignal<libjami::ConversationSignal::OnConversationError>(pimpl_->accountId_, pimpl_->id_, ECOMMIT, err->message); } return {}; } git_reference_free(ref_ptr); auto commit_str = git_oid_tostr_s(&commit_id); if (commit_str) { JAMI_DEBUG("Commit {} amended (new id: {})", id, commit_str); return commit_str; } return {}; } bool ConversationRepository::fetch(const std::string& remoteDeviceId) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); // Fetch distant repository git_remote* remote_ptr = nullptr; git_fetch_options fetch_opts; git_fetch_options_init(&fetch_opts, GIT_FETCH_OPTIONS_VERSION); fetch_opts.follow_redirects = GIT_REMOTE_REDIRECT_NONE; LogOptions options; options.nbOfCommits = 1; auto lastMsg = log(options); if (lastMsg.size() == 0) return false; auto lastCommit = lastMsg[0].id; // Assert that repository exists auto repo = pimpl_->repository(); if (!repo) return false; auto res = git_remote_lookup(&remote_ptr, repo.get(), remoteDeviceId.c_str()); if (res != 0) { if (res != GIT_ENOTFOUND) { JAMI_ERROR("[conv {}] Unable to lookup for remote {}", pimpl_->id_, remoteDeviceId); return false; } std::string channelName = fmt::format("git://{}/{}", remoteDeviceId, pimpl_->id_); if (git_remote_create(&remote_ptr, repo.get(), remoteDeviceId.c_str(), channelName.c_str()) < 0) { JAMI_ERROR("[conv {}] Unable to create remote for repository", pimpl_->id_); return false; } } GitRemote remote {remote_ptr, git_remote_free}; fetch_opts.callbacks.transfer_progress = [](const git_indexer_progress* stats, void*) { // Uncomment to get advancment // if (stats->received_objects % 500 == 0 || stats->received_objects == stats->total_objects) // JAMI_DEBUG("{}/{} {}kb", stats->received_objects, stats->total_objects, // stats->received_bytes/1024); // If a pack is more than 256Mb, it's anormal. if (stats->received_bytes > MAX_FETCH_SIZE) { JAMI_ERROR("Abort fetching repository, the fetch is too big: {} bytes ({}/{})", stats->received_bytes, stats->received_objects, stats->total_objects); return -1; } return 0; }; if (git_remote_fetch(remote.get(), nullptr, &fetch_opts, "fetch") < 0) { const git_error* err = giterr_last(); if (err) { JAMI_WARNING("[conv {}] Unable to fetch remote repository: {:s}", pimpl_->id_, err->message); } return false; } return true; } std::string ConversationRepository::remoteHead(const std::string& remoteDeviceId, const std::string& branch) const { git_remote* remote_ptr = nullptr; auto repo = pimpl_->repository(); if (!repo || git_remote_lookup(&remote_ptr, repo.get(), remoteDeviceId.c_str()) < 0) { JAMI_WARNING("No remote found with id: {}", remoteDeviceId); return {}; } GitRemote remote {remote_ptr, git_remote_free}; git_reference* head_ref_ptr = nullptr; std::string remoteHead = "refs/remotes/" + remoteDeviceId + "/" + branch; git_oid commit_id; if (git_reference_name_to_id(&commit_id, repo.get(), remoteHead.c_str()) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("failed to lookup {} ref: {}", remoteHead, err->message); return {}; } GitReference head_ref {head_ref_ptr, git_reference_free}; auto commit_str = git_oid_tostr_s(&commit_id); if (!commit_str) return {}; return commit_str; } void ConversationRepository::Impl::addUserDevice() { auto account = account_.lock(); if (!account) return; // First, we need to add device file to the repository if not present auto repo = repository(); if (!repo) return; // NOTE: libgit2 uses / for files std::string path = fmt::format("devices/{}.crt", deviceId_); std::filesystem::path devicePath = git_repository_workdir(repo.get()) + path; if (!std::filesystem::is_regular_file(devicePath)) { std::ofstream file(devicePath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", devicePath); return; } auto cert = account->identity().second; auto deviceCert = cert->toString(false); file << deviceCert; file.close(); if (!add(path)) JAMI_WARNING("Unable to add file {}", devicePath); } } void ConversationRepository::Impl::resetHard() { #ifdef LIBJAMI_TESTABLE if (DISABLE_RESET) return; #endif auto repo = repository(); if (!repo) return; git_object *head_commit_obj = nullptr; auto error = git_revparse_single(&head_commit_obj, repo.get(), "HEAD"); if (error < 0) { JAMI_ERROR("Unable to get HEAD commit"); return; } GitObject target {head_commit_obj, git_object_free}; git_reset(repo.get(), head_commit_obj, GIT_RESET_HARD, nullptr); } std::string ConversationRepository::commitMessage(const std::string& msg, bool verifyDevice) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); return pimpl_->commitMessage(msg, verifyDevice); } std::string ConversationRepository::Impl::commitMessage(const std::string& msg, bool verifyDevice) { addUserDevice(); return commit(msg, verifyDevice); } std::vector<std::string> ConversationRepository::commitMessages(const std::vector<std::string>& msgs) { pimpl_->addUserDevice(); std::vector<std::string> ret; ret.reserve(msgs.size()); for (const auto& msg : msgs) ret.emplace_back(pimpl_->commit(msg)); return ret; } std::vector<ConversationCommit> ConversationRepository::log(const LogOptions& options) const { return pimpl_->log(options); } void ConversationRepository::log(PreConditionCb&& preCondition, std::function<void(ConversationCommit&&)>&& emplaceCb, PostConditionCb&& postCondition, const std::string& from, bool logIfNotFound) const { pimpl_->forEachCommit(std::move(preCondition), std::move(emplaceCb), std::move(postCondition), from, logIfNotFound); } std::optional<ConversationCommit> ConversationRepository::getCommit(const std::string& commitId, bool logIfNotFound) const { return pimpl_->getCommit(commitId, logIfNotFound); } std::pair<bool, std::string> ConversationRepository::merge(const std::string& merge_id, bool force) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); // First, the repository must be in a clean state auto repo = pimpl_->repository(); if (!repo) { JAMI_ERROR("[conv {}] Unable to merge without repo", pimpl_->id_); return {false, ""}; } int state = git_repository_state(repo.get()); if (state != GIT_REPOSITORY_STATE_NONE) { pimpl_->resetHard(); int state = git_repository_state(repo.get()); if (state != GIT_REPOSITORY_STATE_NONE) { JAMI_ERROR("[conv {}] Merge operation aborted: repository is in unexpected state {}", pimpl_->id_, state); return {false, ""}; } } // Checkout main (to do a `git_merge branch`) if (git_repository_set_head(repo.get(), "refs/heads/main") < 0) { JAMI_ERROR("[conv {}] Merge operation aborted: unable to checkout main branch", pimpl_->id_); return {false, ""}; } // Then check that merge_id exists git_oid commit_id; if (git_oid_fromstr(&commit_id, merge_id.c_str()) < 0) { JAMI_ERROR("[conv {}] Merge operation aborted: unable to lookup commit {}", pimpl_->id_, merge_id); return {false, ""}; } git_annotated_commit* annotated_ptr = nullptr; if (git_annotated_commit_lookup(&annotated_ptr, repo.get(), &commit_id) < 0) { JAMI_ERROR("[conv {}] Merge operation aborted: unable to lookup commit {}", pimpl_->id_, merge_id); return {false, ""}; } GitAnnotatedCommit annotated {annotated_ptr, git_annotated_commit_free}; // Now, we can analyze which type of merge do we need git_merge_analysis_t analysis; git_merge_preference_t preference; const git_annotated_commit* const_annotated = annotated.get(); if (git_merge_analysis(&analysis, &preference, repo.get(), &const_annotated, 1) < 0) { JAMI_ERROR("[conv {}] Merge operation aborted: repository analysis failed", pimpl_->id_); return {false, ""}; } // Handle easy merges if (analysis & GIT_MERGE_ANALYSIS_UP_TO_DATE) { JAMI_LOG("Already up-to-date"); return {true, ""}; } else if (analysis & GIT_MERGE_ANALYSIS_UNBORN || (analysis & GIT_MERGE_ANALYSIS_FASTFORWARD && !(preference & GIT_MERGE_PREFERENCE_NO_FASTFORWARD))) { if (analysis & GIT_MERGE_ANALYSIS_UNBORN) JAMI_LOG("[conv {}] Merge analysis result: Unborn", pimpl_->id_); else JAMI_LOG("[conv {}] Merge analysis result: Fast-forward", pimpl_->id_); const auto* target_oid = git_annotated_commit_id(annotated.get()); if (!pimpl_->mergeFastforward(target_oid, (analysis & GIT_MERGE_ANALYSIS_UNBORN))) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("[conv {}] Fast forward merge failed: {}", pimpl_->id_, err->message); return {false, ""}; } return {true, ""}; // fast forward so no commit generated; } if (!pimpl_->validateDevice() && !force) { JAMI_ERROR("[conv {}] Invalid device. Not migrated?", pimpl_->id_); return {false, ""}; } // Else we want to check for conflicts git_oid head_commit_id; if (git_reference_name_to_id(&head_commit_id, repo.get(), "HEAD") < 0) { JAMI_ERROR("[conv {}] Unable to get reference for HEAD", pimpl_->id_); return {false, ""}; } git_commit* head_ptr = nullptr; if (git_commit_lookup(&head_ptr, repo.get(), &head_commit_id) < 0) { JAMI_ERROR("[conv {}] Unable to look up HEAD commit", pimpl_->id_); return {false, ""}; } GitCommit head_commit {head_ptr, git_commit_free}; git_commit* other__ptr = nullptr; if (git_commit_lookup(&other__ptr, repo.get(), &commit_id) < 0) { JAMI_ERROR("[conv {}] Unable to look up HEAD commit", pimpl_->id_); return {false, ""}; } GitCommit other_commit {other__ptr, git_commit_free}; git_merge_options merge_opts; git_merge_options_init(&merge_opts, GIT_MERGE_OPTIONS_VERSION); merge_opts.recursion_limit = 2; git_index* index_ptr = nullptr; if (git_merge_commits(&index_ptr, repo.get(), head_commit.get(), other_commit.get(), &merge_opts) < 0) { const git_error* err = giterr_last(); if (err) JAMI_ERROR("[conv {}] Git merge failed: {}", pimpl_->id_, err->message); return {false, ""}; } GitIndex index {index_ptr, git_index_free}; if (git_index_has_conflicts(index.get())) { JAMI_LOG("Some conflicts were detected during the merge operations. Resolution phase."); if (!pimpl_->resolveConflicts(index.get(), merge_id) or !git_add_all(repo.get())) { JAMI_ERROR("Merge operation aborted; Unable to automatically resolve conflicts"); return {false, ""}; } } auto result = pimpl_->createMergeCommit(index.get(), merge_id); JAMI_LOG("Merge done between {} and main", merge_id); return {!result.empty(), result}; } std::string ConversationRepository::mergeBase(const std::string& from, const std::string& to) const { if (auto repo = pimpl_->repository()) { git_oid oid, oidFrom, oidMerge; git_oid_fromstr(&oidFrom, from.c_str()); git_oid_fromstr(&oid, to.c_str()); git_merge_base(&oidMerge, repo.get(), &oid, &oidFrom); if (auto* commit_str = git_oid_tostr_s(&oidMerge)) return commit_str; } return {}; } std::string ConversationRepository::diffStats(const std::string& newId, const std::string& oldId) const { return pimpl_->diffStats(newId, oldId); } std::vector<std::string> ConversationRepository::changedFiles(std::string_view diffStats) { static const std::regex re(" +\\| +[0-9]+.*"); std::vector<std::string> changedFiles; std::string_view line; while (jami::getline(diffStats, line)) { std::svmatch match; if (!std::regex_search(line, match, re) && match.size() == 0) continue; changedFiles.emplace_back(std::regex_replace(std::string {line}, re, "").substr(1)); } return changedFiles; } std::string ConversationRepository::join() { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); // Check that not already member auto repo = pimpl_->repository(); if (!repo) return {}; std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto account = pimpl_->account_.lock(); if (!account) return {}; auto cert = account->identity().second; auto parentCert = cert->issuer; if (!parentCert) { JAMI_ERROR("Parent cert is null!"); return {}; } auto uri = parentCert->getId().toString(); auto membersPath = repoPath / "members"; auto memberFile = membersPath / (uri + ".crt"); auto adminsPath = repoPath / "admins" / (uri + ".crt"); if (std::filesystem::is_regular_file(memberFile) or std::filesystem::is_regular_file(adminsPath)) { // Already member, nothing to commit return {}; } // Remove invited/uri.crt auto invitedPath = repoPath / "invited"; dhtnet::fileutils::remove(fileutils::getFullPath(invitedPath, uri)); // Add members/uri.crt if (!dhtnet::fileutils::recursive_mkdir(membersPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort create conversations", membersPath); return {}; } std::ofstream file(memberFile, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", memberFile); return {}; } file << parentCert->toString(true); file.close(); // git add -A if (!git_add_all(repo.get())) { return {}; } Json::Value json; json["action"] = "join"; json["uri"] = uri; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; { std::lock_guard lk(pimpl_->membersMtx_); auto updated = false; for (auto& member : pimpl_->members_) { if (member.uri == uri) { updated = true; member.role = MemberRole::MEMBER; break; } } if (!updated) pimpl_->members_.emplace_back(ConversationMember {uri, MemberRole::MEMBER}); pimpl_->saveMembers(); } return pimpl_->commitMessage(Json::writeString(wbuilder, json)); } std::string ConversationRepository::leave() { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); // TODO simplify auto account = pimpl_->account_.lock(); auto repo = pimpl_->repository(); if (!account || !repo) return {}; // Remove related files std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto crt = fmt::format("{}.crt", pimpl_->userId_); auto adminFile = repoPath / "admins" / crt; auto memberFile = repoPath / "members" / crt; auto crlsPath = repoPath / "CRLs"; std::error_code ec; if (std::filesystem::is_regular_file(adminFile, ec)) { std::filesystem::remove(adminFile, ec); } if (std::filesystem::is_regular_file(memberFile, ec)) { std::filesystem::remove(memberFile, ec); } // /CRLs for (const auto& crl : account->identity().second->getRevocationLists()) { if (!crl) continue; auto crlPath = crlsPath / pimpl_->deviceId_ / fmt::format("{}.crl", dht::toHex(crl->getNumber())); if (std::filesystem::is_regular_file(crlPath, ec)) { std::filesystem::remove(crlPath, ec); } } // Devices for (const auto& certificate : std::filesystem::directory_iterator(repoPath / "devices", ec)) { if (certificate.is_regular_file(ec)) { try { crypto::Certificate cert(fileutils::loadFile(certificate.path())); if (cert.getIssuerUID() == pimpl_->userId_) std::filesystem::remove(certificate.path(), ec); } catch (...) { continue; } } } if (!git_add_all(repo.get())) { return {}; } Json::Value json; json["action"] = "remove"; json["uri"] = pimpl_->userId_; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; { std::lock_guard lk(pimpl_->membersMtx_); pimpl_->members_.erase(std::remove_if(pimpl_->members_.begin(), pimpl_->members_.end(), [&](auto& member) { return member.uri == pimpl_->userId_; }), pimpl_->members_.end()); pimpl_->saveMembers(); } return pimpl_->commit(Json::writeString(wbuilder, json), false); } void ConversationRepository::erase() { // First, we need to add the member file to the repository if not present if (auto repo = pimpl_->repository()) { std::string repoPath = git_repository_workdir(repo.get()); JAMI_LOG("Erasing {}", repoPath); dhtnet::fileutils::removeAll(repoPath, true); } } ConversationMode ConversationRepository::mode() const { return pimpl_->mode(); } std::string ConversationRepository::voteKick(const std::string& uri, const std::string& type) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); auto repo = pimpl_->repository(); auto account = pimpl_->account_.lock(); if (!account || !repo) return {}; std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto cert = account->identity().second; if (!cert || !cert->issuer) return {}; auto adminUri = cert->issuer->getId().toString(); if (adminUri == uri) { JAMI_WARNING("Admin tried to ban theirself"); return {}; } auto oldFile = repoPath / type / (uri + (type != "invited" ? ".crt" : "")); if (!std::filesystem::is_regular_file(oldFile)) { JAMI_WARNING("Didn't found file for {} with type {}", uri, type); return {}; } auto relativeVotePath = fmt::format("votes/ban/{}/{}", type, uri); auto voteDirectory = repoPath / relativeVotePath; if (!dhtnet::fileutils::recursive_mkdir(voteDirectory, 0700)) { JAMI_ERROR("Error when creating {}. Abort vote", voteDirectory); return {}; } auto votePath = fileutils::getFullPath(voteDirectory, adminUri); std::ofstream voteFile(votePath, std::ios::trunc | std::ios::binary); if (!voteFile.is_open()) { JAMI_ERROR("Unable to write data to {}", votePath); return {}; } voteFile.close(); auto toAdd = fmt::format("{}/{}", relativeVotePath, adminUri); if (!pimpl_->add(toAdd)) return {}; Json::Value json; json["uri"] = uri; json["type"] = "vote"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return pimpl_->commitMessage(Json::writeString(wbuilder, json)); } std::string ConversationRepository::voteUnban(const std::string& uri, const std::string_view type) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); auto repo = pimpl_->repository(); auto account = pimpl_->account_.lock(); if (!account || !repo) return {}; std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto cert = account->identity().second; if (!cert || !cert->issuer) return {}; auto adminUri = cert->issuer->getId().toString(); auto relativeVotePath = fmt::format("votes/unban/{}/{}", type, uri); auto voteDirectory = repoPath / relativeVotePath; if (!dhtnet::fileutils::recursive_mkdir(voteDirectory, 0700)) { JAMI_ERROR("Error when creating {}. Abort vote", voteDirectory); return {}; } auto votePath = voteDirectory / adminUri; std::ofstream voteFile(votePath, std::ios::trunc | std::ios::binary); if (!voteFile.is_open()) { JAMI_ERROR("Unable to write data to {}", votePath); return {}; } voteFile.close(); auto toAdd = fileutils::getFullPath(relativeVotePath, adminUri).string(); if (!pimpl_->add(toAdd.c_str())) return {}; Json::Value json; json["uri"] = uri; json["type"] = "vote"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return pimpl_->commitMessage(Json::writeString(wbuilder, json)); } bool ConversationRepository::Impl::resolveBan(const std::string_view type, const std::string& uri) { auto repo = repository(); std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto bannedPath = repoPath / "banned"; auto devicesPath = repoPath / "devices"; // Move from device or members file into banned auto crtStr = uri + (type != "invited" ? ".crt" : ""); auto originFilePath = repoPath / type / crtStr; auto destPath = bannedPath / type; auto destFilePath = destPath / crtStr; if (!dhtnet::fileutils::recursive_mkdir(destPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort resolving vote", destPath); return false; } std::error_code ec; std::filesystem::rename(originFilePath, destFilePath, ec); if (ec) { JAMI_ERROR("Error when moving {} to {}. Abort resolving vote", originFilePath, destFilePath); return false; } // If members, remove related devices and mark as banned if (type != "devices") { std::error_code ec; for (const auto& certificate : std::filesystem::directory_iterator(devicesPath, ec)) { auto certPath = certificate.path(); try { crypto::Certificate cert(fileutils::loadFile(certPath)); if (auto issuer = cert.issuer) if (issuer->getPublicKey().getId().to_view() == uri) dhtnet::fileutils::remove(certPath, true); } catch (...) { continue; } } std::lock_guard lk(membersMtx_); auto updated = false; for (auto& member : members_) { if (member.uri == uri) { updated = true; member.role = MemberRole::BANNED; break; } } if (!updated) members_.emplace_back(ConversationMember {uri, MemberRole::BANNED}); saveMembers(); } return true; } bool ConversationRepository::Impl::resolveUnban(const std::string_view type, const std::string& uri) { auto repo = repository(); std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto bannedPath = repoPath / "banned"; auto crtStr = uri + (type != "invited" ? ".crt" : ""); auto originFilePath = bannedPath / type / crtStr; auto destPath = repoPath / type; auto destFilePath = destPath / crtStr; if (!dhtnet::fileutils::recursive_mkdir(destPath, 0700)) { JAMI_ERROR("Error when creating {}. Abort resolving vote", destPath); return false; } std::error_code ec; std::filesystem::rename(originFilePath, destFilePath, ec); if (ec) { JAMI_ERROR("Error when moving {} to {}. Abort resolving vote", originFilePath, destFilePath); return false; } std::lock_guard lk(membersMtx_); auto updated = false; auto role = MemberRole::MEMBER; if (type == "invited") role = MemberRole::INVITED; else if (type == "admins") role = MemberRole::ADMIN; for (auto& member : members_) { if (member.uri == uri) { updated = true; member.role = role; break; } } if (!updated) members_.emplace_back(ConversationMember {uri, role}); saveMembers(); return true; } std::string ConversationRepository::resolveVote(const std::string& uri, const std::string_view type, const std::string& voteType) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); // Count ratio admin/votes auto nbAdmins = 0, nbVotes = 0; // For each admin, check if voted auto repo = pimpl_->repository(); if (!repo) return {}; std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto adminsPath = repoPath / "admins"; auto voteDirectory = repoPath / "votes" / voteType / type / uri; for (const auto& certificate : dhtnet::fileutils::readDirectory(adminsPath)) { if (certificate.find(".crt") == std::string::npos) { JAMI_WARNING("Incorrect file found: {}/{}", adminsPath, certificate); continue; } auto adminUri = certificate.substr(0, certificate.size() - std::string(".crt").size()); nbAdmins += 1; if (std::filesystem::is_regular_file(fileutils::getFullPath(voteDirectory, adminUri))) nbVotes += 1; } if (nbAdmins > 0 && (static_cast<double>(nbVotes) / static_cast<double>(nbAdmins)) > .5) { JAMI_WARNING("More than half of the admins voted to ban {}, apply the ban", uri); // Remove vote directory dhtnet::fileutils::removeAll(voteDirectory, true); if (voteType == "ban") { if (!pimpl_->resolveBan(type, uri)) return {}; } else if (voteType == "unban") { if (!pimpl_->resolveUnban(type, uri)) return {}; } // Commit if (!git_add_all(repo.get())) return {}; Json::Value json; json["action"] = voteType; json["uri"] = uri; json["type"] = "member"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return pimpl_->commitMessage(Json::writeString(wbuilder, json)); } // If vote nok return {}; } std::pair<std::vector<ConversationCommit>, bool> ConversationRepository::validFetch(const std::string& remoteDevice) const { auto newCommit = remoteHead(remoteDevice); if (not pimpl_ or newCommit.empty()) return {{}, false}; auto commitsToValidate = pimpl_->behind(newCommit); std::reverse(std::begin(commitsToValidate), std::end(commitsToValidate)); auto isValid = pimpl_->validCommits(commitsToValidate); if (isValid) return {commitsToValidate, false}; return {{}, true}; } bool ConversationRepository::validClone( std::function<void(std::vector<ConversationCommit>)>&& checkCommitCb) const { auto commits = log({}); auto res = pimpl_->validCommits(commits); if (!res) return false; if (checkCommitCb) checkCommitCb(std::move(commits)); return true; } void ConversationRepository::removeBranchWith(const std::string& remoteDevice) { git_remote* remote_ptr = nullptr; auto repo = pimpl_->repository(); if (!repo || git_remote_lookup(&remote_ptr, repo.get(), remoteDevice.c_str()) < 0) { JAMI_WARNING("No remote found with id: {}", remoteDevice); return; } GitRemote remote {remote_ptr, git_remote_free}; git_remote_prune(remote.get(), nullptr); } std::vector<std::string> ConversationRepository::getInitialMembers() const { return pimpl_->getInitialMembers(); } std::vector<ConversationMember> ConversationRepository::members() const { return pimpl_->members(); } std::set<std::string> ConversationRepository::memberUris(std::string_view filter, const std::set<MemberRole>& filteredRoles) const { return pimpl_->memberUris(filter, filteredRoles); } std::map<std::string, std::vector<DeviceId>> ConversationRepository::devices(bool ignoreExpired) const { return pimpl_->devices(ignoreExpired); } void ConversationRepository::refreshMembers() const { try { pimpl_->initMembers(); } catch (...) { } } void ConversationRepository::pinCertificates(bool blocking) { auto acc = pimpl_->account_.lock(); auto repo = pimpl_->repository(); if (!repo or !acc) return; std::string repoPath = git_repository_workdir(repo.get()); std::vector<std::string> paths = {repoPath + "admins", repoPath + "members", repoPath + "devices"}; for (const auto& path : paths) { if (blocking) { std::promise<bool> p; std::future<bool> f = p.get_future(); acc->certStore().pinCertificatePath(path, [&](auto /* certs */) { p.set_value(true); }); f.wait(); } else { acc->certStore().pinCertificatePath(path, {}); } } } std::string ConversationRepository::uriFromDevice(const std::string& deviceId) const { return pimpl_->uriFromDevice(deviceId); } std::string ConversationRepository::updateInfos(const std::map<std::string, std::string>& profile) { std::lock_guard lkOp(pimpl_->opMtx_); pimpl_->resetHard(); auto valid = false; { std::lock_guard lk(pimpl_->membersMtx_); for (const auto& member : pimpl_->members_) { if (member.uri == pimpl_->userId_) { valid = member.role <= pimpl_->updateProfilePermLvl_; break; } } } if (!valid) { JAMI_ERROR("Not enough authorization for updating infos"); emitSignal<libjami::ConversationSignal::OnConversationError>( pimpl_->accountId_, pimpl_->id_, EUNAUTHORIZED, "Not enough authorization for updating infos"); return {}; } auto infosMap = infos(); for (const auto& [k, v] : profile) { infosMap[k] = v; } auto repo = pimpl_->repository(); if (!repo) return {}; std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto profilePath = repoPath / "profile.vcf"; std::ofstream file(profilePath, std::ios::trunc | std::ios::binary); if (!file.is_open()) { JAMI_ERROR("Unable to write data to {}", profilePath); return {}; } auto addKey = [&](auto property, auto key) { auto it = infosMap.find(std::string(key)); if (it != infosMap.end()) { file << property; file << ":"; file << it->second; file << vCard::Delimiter::END_LINE_TOKEN; } }; file << vCard::Delimiter::BEGIN_TOKEN; file << vCard::Delimiter::END_LINE_TOKEN; file << vCard::Property::VCARD_VERSION; file << ":2.1"; file << vCard::Delimiter::END_LINE_TOKEN; addKey(vCard::Property::FORMATTED_NAME, vCard::Value::TITLE); addKey(vCard::Property::DESCRIPTION, vCard::Value::DESCRIPTION); file << vCard::Property::PHOTO; file << vCard::Delimiter::SEPARATOR_TOKEN; file << vCard::Property::BASE64; auto avatarIt = infosMap.find(std::string(vCard::Value::AVATAR)); if (avatarIt != infosMap.end()) { // TODO type=png? store another way? file << ":"; file << avatarIt->second; } file << vCard::Delimiter::END_LINE_TOKEN; addKey(vCard::Property::RDV_ACCOUNT, vCard::Value::RDV_ACCOUNT); file << vCard::Delimiter::END_LINE_TOKEN; addKey(vCard::Property::RDV_DEVICE, vCard::Value::RDV_DEVICE); file << vCard::Delimiter::END_LINE_TOKEN; file << vCard::Delimiter::END_TOKEN; file.close(); if (!pimpl_->add("profile.vcf")) return {}; Json::Value json; json["type"] = "application/update-profile"; Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return pimpl_->commitMessage(Json::writeString(wbuilder, json)); } std::map<std::string, std::string> ConversationRepository::infos() const { if (auto repo = pimpl_->repository()) { try { std::filesystem::path repoPath = git_repository_workdir(repo.get()); auto profilePath = repoPath / "profile.vcf"; std::map<std::string, std::string> result; std::error_code ec; if (std::filesystem::is_regular_file(profilePath, ec)) { auto content = fileutils::loadFile(profilePath); result = ConversationRepository::infosFromVCard(vCard::utils::toMap( std::string_view {(const char*) content.data(), content.size()})); } result["mode"] = std::to_string(static_cast<int>(mode())); return result; } catch (...) { } } return {}; } std::map<std::string, std::string> ConversationRepository::infosFromVCard(std::map<std::string, std::string>&& details) { std::map<std::string, std::string> result; for (auto&& [k, v] : details) { if (k == vCard::Property::FORMATTED_NAME) { result["title"] = std::move(v); } else if (k == vCard::Property::DESCRIPTION) { result["description"] = std::move(v); } else if (k.find(vCard::Property::PHOTO) == 0) { result["avatar"] = std::move(v); } else if (k.find(vCard::Property::RDV_ACCOUNT) == 0) { result["rdvAccount"] = std::move(v); } else if (k.find(vCard::Property::RDV_DEVICE) == 0) { result["rdvDevice"] = std::move(v); } } return result; } std::string ConversationRepository::getHead() const { if (auto repo = pimpl_->repository()) { git_oid commit_id; if (git_reference_name_to_id(&commit_id, repo.get(), "HEAD") < 0) { JAMI_ERROR("Unable to get reference for HEAD"); return {}; } if (auto commit_str = git_oid_tostr_s(&commit_id)) return commit_str; } return {}; } std::optional<std::map<std::string, std::string>> ConversationRepository::convCommitToMap(const ConversationCommit& commit) const { return pimpl_->convCommitToMap(commit); } std::vector<std::map<std::string, std::string>> ConversationRepository::convCommitsToMap(const std::vector<ConversationCommit>& commits) const { std::vector<std::map<std::string, std::string>> result = {}; result.reserve(commits.size()); for (const auto& commit : commits) { auto message = pimpl_->convCommitToMap(commit); if (message == std::nullopt) continue; result.emplace_back(*message); } return result; } } // namespace jami
150,861
C++
.cpp
3,658
31.740022
124
0.578579
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,808
accountarchive.cpp
savoirfairelinux_jami-daemon/src/jamidht/accountarchive.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "accountarchive.h" #include "account_const.h" #include "configkeys.h" #include "base64.h" #include "logger.h" #include <json/json.h> namespace jami { void AccountArchive::deserialize(const std::vector<uint8_t>& dat, const std::vector<uint8_t>& salt) { JAMI_DEBUG("Loading account archive ({:d} bytes)", dat.size()); password_salt = salt; // Decode string auto* char_data = reinterpret_cast<const char*>(&dat[0]); std::string err; Json::Value value; Json::CharReaderBuilder rbuilder; Json::CharReaderBuilder::strictMode(&rbuilder.settings_); auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader()); if (!reader->parse(char_data, char_data + dat.size(), &value, &err)) { JAMI_ERR() << "Archive JSON parsing error: " << err; throw std::runtime_error("failed to parse JSON"); } // Import content try { for (Json::ValueIterator itr = value.begin(); itr != value.end(); itr++) { try { const auto key = itr.key().asString(); if (key.empty()) continue; if (key.compare(libjami::Account::ConfProperties::TLS::CA_LIST_FILE) == 0) { } else if (key.compare(libjami::Account::ConfProperties::TLS::PRIVATE_KEY_FILE) == 0) { } else if (key.compare(libjami::Account::ConfProperties::TLS::CERTIFICATE_FILE) == 0) { } else if (key.compare(libjami::Account::ConfProperties::DHT_PROXY_LIST_URL) == 0) { } else if (key.compare(libjami::Account::ConfProperties::AUTOANSWER) == 0) { } else if (key.compare(libjami::Account::ConfProperties::PROXY_ENABLED) == 0) { } else if (key.compare(libjami::Account::ConfProperties::PROXY_SERVER) == 0) { } else if (key.compare(libjami::Account::ConfProperties::PROXY_PUSH_TOKEN) == 0) { } else if (key.compare(Conf::RING_CA_KEY) == 0) { ca_key = std::make_shared<dht::crypto::PrivateKey>( base64::decode(itr->asString())); } else if (key.compare(Conf::RING_ACCOUNT_KEY) == 0) { id.first = std::make_shared<dht::crypto::PrivateKey>( base64::decode(itr->asString())); } else if (key.compare(Conf::RING_ACCOUNT_CERT) == 0) { id.second = std::make_shared<dht::crypto::Certificate>( base64::decode(itr->asString())); } else if (key.compare(Conf::RING_ACCOUNT_CONTACTS) == 0) { for (Json::ValueIterator citr = itr->begin(); citr != itr->end(); citr++) { dht::InfoHash h {citr.key().asString()}; if (h != dht::InfoHash {}) contacts.emplace(h, Contact {*citr}); } } else if (key.compare(Conf::CONVERSATIONS_KEY) == 0) { for (Json::ValueIterator citr = itr->begin(); citr != itr->end(); citr++) { auto ci = ConvInfo(*citr); conversations[ci.id] = std::move(ci); } } else if (key.compare(Conf::CONVERSATIONS_REQUESTS_KEY) == 0) { for (Json::ValueIterator citr = itr->begin(); citr != itr->end(); citr++) { conversationsRequests.emplace(citr.key().asString(), ConversationRequest(*citr)); } } else if (key.compare(Conf::ETH_KEY) == 0) { eth_key = base64::decode(itr->asString()); } else if (key.compare(Conf::RING_ACCOUNT_CRL) == 0) { revoked = std::make_shared<dht::crypto::RevocationList>( base64::decode(itr->asString())); } else { config[key] = itr->asString(); } } catch (const std::exception& ex) { JAMI_ERR("Unable to parse JSON entry with value of type %d: %s", (unsigned) itr->type(), ex.what()); } } } catch (const std::exception& ex) { JAMI_ERR("Unable to parse JSON: %s", ex.what()); } if (not id.first) { throw std::runtime_error("Archive doesn't include account private key"); } } std::string AccountArchive::serialize() const { Json::Value root; for (const auto& it : config) root[it.first] = it.second; if (ca_key and *ca_key) root[Conf::RING_CA_KEY] = base64::encode(ca_key->serialize()); root[Conf::RING_ACCOUNT_KEY] = base64::encode(id.first->serialize()); root[Conf::RING_ACCOUNT_CERT] = base64::encode(id.second->getPacked()); root[Conf::ETH_KEY] = base64::encode(eth_key); if (revoked) root[Conf::RING_ACCOUNT_CRL] = base64::encode(revoked->getPacked()); if (not contacts.empty()) { Json::Value& jsonContacts = root[Conf::RING_ACCOUNT_CONTACTS]; for (const auto& c : contacts) jsonContacts[c.first.toString()] = c.second.toJson(); } if (not conversations.empty()) { Json::Value& jsonConversations = root[Conf::CONVERSATIONS_KEY]; for (const auto& [key, c] : conversations) { jsonConversations[key] = c.toJson(); } } if (not conversationsRequests.empty()) { Json::Value& jsonConversationsReqs = root[Conf::CONVERSATIONS_REQUESTS_KEY]; for (const auto& [key, value] : conversationsRequests) { jsonConversationsReqs[key] = value.toJson(); } } Json::StreamWriterBuilder wbuilder; wbuilder["commentStyle"] = "None"; wbuilder["indentation"] = ""; return Json::writeString(wbuilder, root); } } // namespace jami
6,581
C++
.cpp
136
37.676471
103
0.572896
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,809
sync_channel_handler.cpp
savoirfairelinux_jami-daemon/src/jamidht/sync_channel_handler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "jamidht/sync_channel_handler.h" #include <opendht/thread_pool.h> static constexpr const char SYNC_SCHEME[] {"sync://"}; namespace jami { SyncChannelHandler::SyncChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm) : ChannelHandlerInterface() , account_(acc) , connectionManager_(cm) {} SyncChannelHandler::~SyncChannelHandler() {} void SyncChannelHandler::connect(const DeviceId& deviceId, const std::string&, ConnectCb&& cb) { auto channelName = SYNC_SCHEME + deviceId.toString(); if (connectionManager_.isConnecting(deviceId, channelName)) { JAMI_LOG("Already connecting to {}", deviceId); return; } connectionManager_.connectDevice(deviceId, channelName, std::move(cb)); } bool SyncChannelHandler::onRequest(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& /* name */) { auto acc = account_.lock(); if (!cert || !cert->issuer || !acc) return false; return cert->issuer->getId().toString() == acc->getUsername(); } void SyncChannelHandler::onReady(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string&, std::shared_ptr<dhtnet::ChannelSocket> channel) { auto acc = account_.lock(); if (!cert || !cert->issuer || !acc) return; if (auto sm = acc->syncModule()) sm->cacheSyncConnection(std::move(channel), cert->issuer->getId().toString(), cert->getLongId()); dht::ThreadPool::io().run([account=account_, channel]() { if (auto acc = account.lock()) acc->sendProfile("", acc->getUsername(), channel->deviceId().toString()); }); } } // namespace jami
2,643
C++
.cpp
66
32.909091
89
0.637354
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,812
Common.cpp
savoirfairelinux_jami-daemon/src/jamidht/eth/libdevcrypto/Common.cpp
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Common.cpp * @author Alex Leverington <nessence@gmail.com> * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "Common.h" #include <secp256k1.h> #include <libdevcore/SHA3.h> #include <memory> using namespace std; using namespace dev; using namespace dev::crypto; namespace { secp256k1_context const* getCtx() { struct secp256k1Deleter { void operator()(secp256k1_context* b) { secp256k1_context_destroy(b); } }; static std::unique_ptr<secp256k1_context, secp256k1Deleter> s_ctx(secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY)); return s_ctx.get(); } } // namespace bool dev::SignatureStruct::isValid() const noexcept { static const h256 s_max {"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"}; static const h256 s_zero; return (v <= 1 && r > s_zero && s > s_zero && r < s_max && s < s_max); } Public dev::toPublic(Secret const& _secret) { auto* ctx = getCtx(); secp256k1_pubkey rawPubkey; // Creation will fail if the secret key is invalid. if (!secp256k1_ec_pubkey_create(ctx, &rawPubkey, _secret.data())) return {}; std::array<uint8_t, 65> serializedPubkey; size_t serializedPubkeySize = serializedPubkey.size(); secp256k1_ec_pubkey_serialize(ctx, serializedPubkey.data(), &serializedPubkeySize, &rawPubkey, SECP256K1_EC_UNCOMPRESSED); assert(serializedPubkeySize == serializedPubkey.size()); // Expect single byte header of value 0x04 -- uncompressed public key. assert(serializedPubkey[0] == 0x04); // Create the Public skipping the header. return Public {&serializedPubkey[1], Public::ConstructFromPointer}; } Address dev::toAddress(Public const& _public) { return right160(sha3(_public.ref())); } Address dev::toAddress(Secret const& _secret) { return toAddress(toPublic(_secret)); } KeyPair::KeyPair(Secret const& _sec) : m_secret(_sec) , m_public(toPublic(_sec)) { // Assign address only if the secret key is valid. if (m_public) m_address = toAddress(m_public); } KeyPair KeyPair::create() { while (true) { KeyPair keyPair(Secret::random()); if (keyPair.address()) return keyPair; } }
3,078
C++
.cpp
92
28.478261
99
0.686406
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,813
routing_table.cpp
savoirfairelinux_jami-daemon/src/jamidht/swarm/routing_table.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "routing_table.h" #include <dhtnet/multiplexed_socket.h> #include <opendht/infohash.h> #include <math.h> #include <stdio.h> #include <iostream> #include <iterator> #include <stdlib.h> #include <time.h> constexpr const std::chrono::minutes FIND_PERIOD {10}; using namespace std::placeholders; namespace jami { using namespace dht; Bucket::Bucket(const NodeId& id) : lowerLimit_(id) {} bool Bucket::addNode(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) { return addNode(NodeInfo(socket)); } bool Bucket::addNode(NodeInfo&& info) { auto nodeId = info.socket->deviceId(); if (nodes.try_emplace(nodeId, std::move(info)).second) { connecting_nodes.erase(nodeId); known_nodes.erase(nodeId); mobile_nodes.erase(nodeId); return true; } return false; } bool Bucket::removeNode(const NodeId& nodeId) { auto node = nodes.find(nodeId); auto isMobile = node->second.isMobile_; if (node == nodes.end()) return false; nodes.erase(nodeId); if (isMobile) { addMobileNode(nodeId); } else { addKnownNode(nodeId); } return true; } std::set<NodeId> Bucket::getNodeIds() const { std::set<NodeId> nodesId; for (auto const& key : nodes) nodesId.insert(key.first); return nodesId; } bool Bucket::hasNode(const NodeId& nodeId) const { return nodes.find(nodeId) != nodes.end(); } bool Bucket::addKnownNode(const NodeId& nodeId) { if (!hasNode(nodeId)) { if (known_nodes.emplace(nodeId).second) { return true; } } return false; } NodeId Bucket::getKnownNode(unsigned index) const { if (index > known_nodes.size()) { throw std::out_of_range("End of table for get known Node Id " + std::to_string(index)); } auto it = known_nodes.begin(); std::advance(it, index); return *it; } bool Bucket::addMobileNode(const NodeId& nodeId) { if (!hasNode(nodeId)) { if (mobile_nodes.emplace(nodeId).second) { known_nodes.erase(nodeId); return true; } } return false; } bool Bucket::addConnectingNode(const NodeId& nodeId) { if (!hasNode(nodeId)) { if (connecting_nodes.emplace(nodeId).second) { known_nodes.erase(nodeId); mobile_nodes.erase(nodeId); return true; } } return false; } std::set<NodeId> Bucket::getKnownNodesRandom(unsigned numberNodes, std::mt19937_64& rd) const { std::set<NodeId> nodesToReturn; if (getKnownNodesSize() <= numberNodes) return getKnownNodes(); std::uniform_int_distribution<unsigned> distrib(0, getKnownNodesSize() - 1); while (nodesToReturn.size() < numberNodes) { nodesToReturn.emplace(getKnownNode(distrib(rd))); } return nodesToReturn; } asio::steady_timer& Bucket::getNodeTimer(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) { auto node = nodes.find(socket->deviceId()); if (node == nodes.end()) { throw std::range_error("Unable to find timer " + socket->deviceId().toString()); } return node->second.refresh_timer; } bool Bucket::shutdownNode(const NodeId& nodeId) { auto node = nodes.find(nodeId); if (node != nodes.end()) { auto socket = node->second.socket; auto node = socket->deviceId(); socket->shutdown(); removeNode(node); return true; } return false; } void Bucket::shutdownAllNodes() { while (not nodes.empty()) { auto it = nodes.begin(); auto socket = it->second.socket; auto nodeId = socket->deviceId(); socket->shutdown(); removeNode(nodeId); } } void Bucket::printBucket(unsigned number) const { JAMI_ERROR("BUCKET Number: {:d}", number); unsigned nodeNum = 1; for (auto it = nodes.begin(); it != nodes.end(); ++it) { JAMI_DEBUG("Node {:s} Id: {:s} isMobile: {:s}", std::to_string(nodeNum), it->first.toString(), std::to_string(it->second.isMobile_)); nodeNum++; } JAMI_ERROR("Mobile Nodes"); nodeNum = 0; for (auto it = mobile_nodes.begin(); it != mobile_nodes.end(); ++it) { JAMI_DEBUG("Node {:s} Id: {:s}", std::to_string(nodeNum), (*it).toString()); nodeNum++; } JAMI_ERROR("Known Nodes"); nodeNum = 0; for (auto it = known_nodes.begin(); it != known_nodes.end(); ++it) { JAMI_DEBUG("Node {:s} Id: {:s}", std::to_string(nodeNum), (*it).toString()); nodeNum++; } JAMI_ERROR("Connecting_nodes"); nodeNum = 0; for (auto it = connecting_nodes.begin(); it != connecting_nodes.end(); ++it) { JAMI_DEBUG("Node {:s} Id: {:s}", std::to_string(nodeNum), (*it).toString()); nodeNum++; } }; void Bucket::changeMobility(const NodeId& nodeId, bool isMobile) { auto itn = nodes.find(nodeId); if (itn != nodes.end()) { itn->second.isMobile_ = isMobile; } } // For tests std::set<std::shared_ptr<dhtnet::ChannelSocketInterface>> Bucket::getNodeSockets() const { std::set<std::shared_ptr<dhtnet::ChannelSocketInterface>> sockets; for (auto const& info : nodes) sockets.insert(info.second.socket); return sockets; } // #################################################################################################### RoutingTable::RoutingTable() { buckets.emplace_back(NodeId::zero()); } bool RoutingTable::addNode(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) { auto bucket = findBucket(socket->deviceId()); return addNode(socket, bucket); } bool RoutingTable::addNode(const std::shared_ptr<dhtnet::ChannelSocketInterface>& channel, std::list<Bucket>::iterator& bucket) { NodeId nodeId = channel->deviceId(); if (bucket->hasNode(nodeId) || id_ == nodeId) { return false; } while (bucket->isFull()) { if (contains(bucket, id_)) { split(bucket); bucket = findBucket(nodeId); } else { return bucket->addNode(std::move(channel)); } } return bucket->addNode(std::move(channel)); } bool RoutingTable::removeNode(const NodeId& nodeId) { return findBucket(nodeId)->removeNode(nodeId); } bool RoutingTable::hasNode(const NodeId& nodeId) { return findBucket(nodeId)->hasNode(nodeId); } bool RoutingTable::addKnownNode(const NodeId& nodeId) { if (id_ == nodeId) return false; auto bucket = findBucket(nodeId); if (bucket == buckets.end()) return false; return bucket->addKnownNode(nodeId); } bool RoutingTable::addMobileNode(const NodeId& nodeId) { if (id_ == nodeId) return false; auto bucket = findBucket(nodeId); if (bucket == buckets.end()) return 0; bucket->addMobileNode(nodeId); return 1; } void RoutingTable::removeMobileNode(const NodeId& nodeId) { return findBucket(nodeId)->removeMobileNode(nodeId); } bool RoutingTable::hasMobileNode(const NodeId& nodeId) { return findBucket(nodeId)->hasMobileNode(nodeId); }; bool RoutingTable::addConnectingNode(const NodeId& nodeId) { if (id_ == nodeId) return false; auto bucket = findBucket(nodeId); if (bucket == buckets.end()) return 0; bucket->addConnectingNode(nodeId); return 1; } void RoutingTable::removeConnectingNode(const NodeId& nodeId) { findBucket(nodeId)->removeConnectingNode(nodeId); } std::list<Bucket>::iterator RoutingTable::findBucket(const NodeId& nodeId) { if (buckets.empty()) throw std::runtime_error("No bucket"); auto b = buckets.begin(); while (true) { auto next = std::next(b); if (next == buckets.end()) return b; if (std::memcmp(nodeId.data(), next->getLowerLimit().data(), nodeId.size()) < 0) return b; b = next; } } std::vector<NodeId> RoutingTable::closestNodes(const NodeId& nodeId, unsigned count) { std::vector<NodeId> closestNodes; auto bucket = findBucket(nodeId); auto sortedBucketInsert = [&](const std::list<Bucket>::iterator& b) { auto nodes = b->getNodeIds(); for (auto n : nodes) { if (n != nodeId) { auto here = std::find_if(closestNodes.begin(), closestNodes.end(), [&nodeId, &n](NodeId& NodeId) { return nodeId.xorCmp(n, NodeId) < 0; }); closestNodes.insert(here, n); } } }; auto itn = bucket; auto itp = (bucket == buckets.begin()) ? buckets.end() : std::prev(bucket); while (itn != buckets.end() || itp != buckets.end()) { if (itn != buckets.end()) { sortedBucketInsert(itn); itn = std::next(itn); } if (itp != buckets.end()) { sortedBucketInsert(itp); itp = (itp == buckets.begin()) ? buckets.end() : std::prev(itp); } } if (closestNodes.size() > count) { closestNodes.resize(count); } return closestNodes; } void RoutingTable::printRoutingTable() const { int counter = 1; JAMI_DEBUG("SWARM: {:s} ", id_.toString()); for (auto it = buckets.begin(); it != buckets.end(); ++it) { it->printBucket(counter); counter++; } JAMI_DEBUG("_____________________________________________________________________________"); } void RoutingTable::shutdownNode(const NodeId& nodeId) { findBucket(nodeId)->shutdownNode(nodeId); } std::vector<NodeId> RoutingTable::getNodes() const { std::lock_guard lock(mutex_); std::vector<NodeId> ret; for (const auto& b : buckets) { const auto& nodes = b.getNodeIds(); ret.insert(ret.end(), nodes.begin(), nodes.end()); } return ret; } std::vector<NodeId> RoutingTable::getKnownNodes() const { std::vector<NodeId> ret; for (const auto& b : buckets) { const auto& nodes = b.getKnownNodes(); ret.insert(ret.end(), nodes.begin(), nodes.end()); } return ret; } std::vector<NodeId> RoutingTable::getMobileNodes() const { std::vector<NodeId> ret; for (const auto& b : buckets) { const auto& nodes = b.getMobileNodes(); ret.insert(ret.end(), nodes.begin(), nodes.end()); } return ret; } std::vector<NodeId> RoutingTable::getConnectingNodes() const { std::vector<NodeId> ret; for (const auto& b : buckets) { const auto& nodes = b.getConnectingNodes(); ret.insert(ret.end(), nodes.begin(), nodes.end()); } return ret; } std::vector<NodeId> RoutingTable::getBucketMobileNodes() const { std::vector<NodeId> ret; auto bucket = findBucket(id_); const auto& nodes = bucket->getMobileNodes(); ret.insert(ret.end(), nodes.begin(), nodes.end()); return ret; } bool RoutingTable::contains(const std::list<Bucket>::iterator& bucket, const NodeId& nodeId) const { return NodeId::cmp(bucket->getLowerLimit(), nodeId) <= 0 && (std::next(bucket) == buckets.end() || NodeId::cmp(nodeId, std::next(bucket)->getLowerLimit()) < 0); } std::vector<NodeId> RoutingTable::getAllNodes() const { std::vector<NodeId> ret; for (const auto& b : buckets) { const auto& nodes = b.getNodeIds(); const auto& knownNodes = b.getKnownNodes(); const auto& mobileNodes = b.getMobileNodes(); const auto& connectingNodes = b.getConnectingNodes(); ret.reserve(nodes.size() + knownNodes.size() + mobileNodes.size() + connectingNodes.size()); ret.insert(ret.end(), nodes.begin(), nodes.end()); ret.insert(ret.end(), knownNodes.begin(), knownNodes.end()); ret.insert(ret.end(), mobileNodes.begin(), mobileNodes.end()); ret.insert(ret.end(), connectingNodes.begin(), connectingNodes.end()); } return ret; } void RoutingTable::deleteNode(const NodeId& nodeId) { auto bucket = findBucket(nodeId); bucket->shutdownNode(nodeId); bucket->removeConnectingNode(nodeId); bucket->removeKnownNode(nodeId); bucket->removeMobileNode(nodeId); } NodeId RoutingTable::middle(std::list<Bucket>::iterator& it) const { unsigned bit = depth(it); if (bit >= 8 * HASH_LEN) throw std::out_of_range("End of table"); NodeId id = it->getLowerLimit(); id.setBit(bit, true); return id; } unsigned RoutingTable::depth(std::list<Bucket>::iterator& bucket) const { int bit1 = bucket->getLowerLimit().lowbit(); int bit2 = std::next(bucket) != buckets.end() ? std::next(bucket)->getLowerLimit().lowbit() : -1; return std::max(bit1, bit2) + 1; } bool RoutingTable::split(std::list<Bucket>::iterator& bucket) { NodeId id = middle(bucket); auto newBucketIt = buckets.emplace(std::next(bucket), id); // Re-assign nodes auto& nodeSwap = bucket->getNodes(); for (auto it = nodeSwap.begin(); it != nodeSwap.end();) { auto& node = *it; auto nodeId = it->first; if (!contains(bucket, nodeId)) { newBucketIt->addNode(std::move(node.second)); it = nodeSwap.erase(it); } else { ++it; } } auto connectingSwap = bucket->getConnectingNodes(); for (auto it = connectingSwap.begin(); it != connectingSwap.end();) { auto nodeId = *it; if (!contains(bucket, nodeId)) { newBucketIt->addConnectingNode(nodeId); it = connectingSwap.erase(it); bucket->removeConnectingNode(nodeId); } else { ++it; } } auto knownSwap = bucket->getKnownNodes(); for (auto it = knownSwap.begin(); it != knownSwap.end();) { auto nodeId = *it; if (!contains(bucket, nodeId)) { newBucketIt->addKnownNode(nodeId); it = knownSwap.erase(it); bucket->removeKnownNode(nodeId); } else { ++it; } } auto mobileSwap = bucket->getMobileNodes(); for (auto it = mobileSwap.begin(); it != mobileSwap.end();) { auto nodeId = *it; if (!contains(bucket, nodeId)) { newBucketIt->addMobileNode(nodeId); it = mobileSwap.erase(it); bucket->removeMobileNode(nodeId); } else { ++it; } } return true; } } // namespace jami
15,215
C++
.cpp
516
24.087209
144
0.620739
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,814
swarm_manager.cpp
savoirfairelinux_jami-daemon/src/jamidht/swarm/swarm_manager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "swarm_manager.h" #include <dhtnet/multiplexed_socket.h> #include <opendht/thread_pool.h> constexpr const std::chrono::minutes FIND_PERIOD {10}; namespace jami { using namespace swarm_protocol; SwarmManager::SwarmManager(const NodeId& id, const std::mt19937_64& rand, ToConnectCb&& toConnectCb) : id_(id) , rd(rand) , toConnectCb_(toConnectCb) { routing_table.setId(id); } SwarmManager::~SwarmManager() { if (!isShutdown_) shutdown(); } bool SwarmManager::setKnownNodes(const std::vector<NodeId>& known_nodes) { isShutdown_ = false; std::vector<NodeId> newNodes; { std::lock_guard lock(mutex); for (const auto& nodeId : known_nodes) { if (addKnownNode(nodeId)) { newNodes.emplace_back(nodeId); } } } if (newNodes.empty()) return false; dht::ThreadPool::io().run([w=weak(), newNodes=std::move(newNodes)] { auto shared = w.lock(); if (!shared) return; // If we detect a new node which already got a TCP link // we can use it to speed-up the bootstrap (because opening // a new channel will be easy) std::set<NodeId> toConnect; for (const auto& nodeId: newNodes) { if (shared->toConnectCb_ && shared->toConnectCb_(nodeId)) toConnect.emplace(nodeId); } shared->maintainBuckets(toConnect); }); return true; } void SwarmManager::setMobileNodes(const std::vector<NodeId>& mobile_nodes) { { std::lock_guard lock(mutex); for (const auto& nodeId : mobile_nodes) addMobileNodes(nodeId); } } void SwarmManager::addChannel(const std::shared_ptr<dhtnet::ChannelSocketInterface>& channel) { // JAMI_WARNING("[SwarmManager {}] addChannel! with {}", fmt::ptr(this), channel->deviceId().to_view()); if (channel) { auto emit = false; { std::lock_guard lock(mutex); emit = routing_table.findBucket(getId())->isEmpty(); auto bucket = routing_table.findBucket(channel->deviceId()); if (routing_table.addNode(channel, bucket)) { std::error_code ec; resetNodeExpiry(ec, channel, id_); } } receiveMessage(channel); if (emit && onConnectionChanged_) { // If it's the first channel we add, we're now connected! JAMI_DEBUG("[SwarmManager {}] Bootstrap: Connected!", fmt::ptr(this)); onConnectionChanged_(true); } } } void SwarmManager::removeNode(const NodeId& nodeId) { std::unique_lock lk(mutex); if (isConnectedWith(nodeId)) { removeNodeInternal(nodeId); lk.unlock(); maintainBuckets(); } } void SwarmManager::changeMobility(const NodeId& nodeId, bool isMobile) { std::lock_guard lock(mutex); auto bucket = routing_table.findBucket(nodeId); bucket->changeMobility(nodeId, isMobile); } bool SwarmManager::isConnectedWith(const NodeId& deviceId) { return routing_table.hasNode(deviceId); } void SwarmManager::shutdown() { if (isShutdown_) { return; } isShutdown_ = true; std::lock_guard lock(mutex); routing_table.shutdownAllNodes(); } void SwarmManager::restart() { isShutdown_ = false; } bool SwarmManager::addKnownNode(const NodeId& nodeId) { return routing_table.addKnownNode(nodeId); } void SwarmManager::addMobileNodes(const NodeId& nodeId) { if (id_ != nodeId) { routing_table.addMobileNode(nodeId); } } void SwarmManager::maintainBuckets(const std::set<NodeId>& toConnect) { std::set<NodeId> nodes = toConnect; std::unique_lock lock(mutex); auto& buckets = routing_table.getBuckets(); for (auto it = buckets.begin(); it != buckets.end(); ++it) { auto& bucket = *it; bool myBucket = routing_table.contains(it, id_); auto connecting_nodes = myBucket ? bucket.getConnectingNodesSize() : bucket.getConnectingNodesSize() + bucket.getNodesSize(); if (connecting_nodes < Bucket::BUCKET_MAX_SIZE) { auto nodesToTry = bucket.getKnownNodesRandom(Bucket::BUCKET_MAX_SIZE - connecting_nodes, rd); for (auto& node : nodesToTry) routing_table.addConnectingNode(node); nodes.insert(nodesToTry.begin(), nodesToTry.end()); } } lock.unlock(); for (auto& node : nodes) tryConnect(node); } void SwarmManager::sendRequest(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, NodeId& nodeId, Query q, int numberNodes) { msgpack::sbuffer buffer; msgpack::packer<msgpack::sbuffer> pk(&buffer); std::error_code ec; Request toRequest {q, numberNodes, nodeId}; Message msg; msg.is_mobile = isMobile_; msg.request = std::move(toRequest); pk.pack(msg); socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{}", ec.message()); return; } } void SwarmManager::sendAnswer(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, const Message& msg_) { std::lock_guard lock(mutex); if (msg_.request->q == Query::FIND) { auto nodes = routing_table.closestNodes(msg_.request->nodeId, msg_.request->num); auto bucket = routing_table.findBucket(msg_.request->nodeId); const auto& m_nodes = bucket->getMobileNodes(); Response toResponse {Query::FOUND, nodes, {m_nodes.begin(), m_nodes.end()}}; Message msg; msg.is_mobile = isMobile_; msg.response = std::move(toResponse); msgpack::sbuffer buffer((size_t) 60000); msgpack::packer<msgpack::sbuffer> pk(&buffer); pk.pack(msg); std::error_code ec; socket->write(reinterpret_cast<const unsigned char*>(buffer.data()), buffer.size(), ec); if (ec) { JAMI_ERROR("{}", ec.message()); return; } } else { } } void SwarmManager::receiveMessage(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) { struct DecodingContext { msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t, void*) { return true; }, nullptr, 512}; }; socket->setOnRecv([w = weak(), wsocket = std::weak_ptr<dhtnet::ChannelSocketInterface>(socket), ctx = std::make_shared<DecodingContext>()](const uint8_t* buf, size_t len) { ctx->pac.reserve_buffer(len); std::copy_n(buf, len, ctx->pac.buffer()); ctx->pac.buffer_consumed(len); msgpack::object_handle oh; while (ctx->pac.next(oh)) { auto shared = w.lock(); auto socket = wsocket.lock(); if (!shared || !socket) return size_t {0}; try { Message msg; oh.get().convert(msg); if (msg.is_mobile) shared->changeMobility(socket->deviceId(), msg.is_mobile); if (msg.request) { shared->sendAnswer(socket, msg); } else if (msg.response) { shared->setKnownNodes(msg.response->nodes); shared->setMobileNodes(msg.response->mobile_nodes); } } catch (const std::exception& e) { JAMI_WARNING("Error DRT recv: {}", e.what()); return len; } } return len; }); socket->onShutdown([w = weak(), deviceId = socket->deviceId()] { dht::ThreadPool::io().run([w, deviceId] { auto shared = w.lock(); if (shared && !shared->isShutdown_) { shared->removeNode(deviceId); } }); }); } void SwarmManager::resetNodeExpiry(const asio::error_code& ec, const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, NodeId node) { NodeId idToFind; std::list<Bucket>::iterator bucket; if (ec == asio::error::operation_aborted) return; if (!node) { bucket = routing_table.findBucket(socket->deviceId()); idToFind = bucket->randomId(rd); } else { bucket = routing_table.findBucket(node); idToFind = node; } sendRequest(socket, idToFind, Query::FIND, Bucket::BUCKET_MAX_SIZE); if (!node) { auto& nodeTimer = bucket->getNodeTimer(socket); nodeTimer.expires_after(FIND_PERIOD); nodeTimer.async_wait(std::bind(&jami::SwarmManager::resetNodeExpiry, shared_from_this(), std::placeholders::_1, socket, NodeId {})); } } void SwarmManager::tryConnect(const NodeId& nodeId) { if (needSocketCb_) needSocketCb_(nodeId.toString(), [w = weak(), nodeId](const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket) { auto shared = w.lock(); if (!shared || shared->isShutdown_) return true; if (socket) { shared->addChannel(socket); return true; } std::unique_lock lk(shared->mutex); auto bucket = shared->routing_table.findBucket(nodeId); bucket->removeConnectingNode(nodeId); bucket->addKnownNode(nodeId); bucket = shared->routing_table.findBucket(shared->getId()); if (bucket->getConnectingNodesSize() == 0 && bucket->isEmpty() && shared->onConnectionChanged_) { lk.unlock(); JAMI_WARNING("[SwarmManager {:p}] Bootstrap: all connections failed", fmt::ptr(shared.get())); shared->onConnectionChanged_(false); } return true; }); } void SwarmManager::removeNodeInternal(const NodeId& nodeId) { routing_table.removeNode(nodeId); } std::vector<NodeId> SwarmManager::getAllNodes() const { std::lock_guard lock(mutex); return routing_table.getAllNodes(); } void SwarmManager::deleteNode(std::vector<NodeId> nodes) { { std::lock_guard lock(mutex); for (const auto& node : nodes) { routing_table.deleteNode(node); } } maintainBuckets(); } } // namespace jami
11,725
C++
.cpp
340
25.485294
108
0.578841
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,815
swarm_channel_handler.cpp
savoirfairelinux_jami-daemon/src/jamidht/swarm/swarm_channel_handler.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "swarm_channel_handler.h" namespace jami { SwarmChannelHandler::SwarmChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm) : ChannelHandlerInterface() , account_(acc) , connectionManager_(cm) {} SwarmChannelHandler::~SwarmChannelHandler() {} void SwarmChannelHandler::connect(const DeviceId& deviceId, const std::string& conversationId, ConnectCb&& cb) { #ifdef LIBJAMI_TESTABLE if (disableSwarmManager) return; #endif connectionManager_.connectDevice(deviceId, fmt::format("swarm://{}", conversationId), cb); } bool SwarmChannelHandler::onRequest(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& name) { #ifdef LIBJAMI_TESTABLE if (disableSwarmManager) return false; #endif auto acc = account_.lock(); if (!cert || !cert->issuer || !acc) return false; auto sep = name.find_last_of('/'); auto conversationId = name.substr(sep + 1); if (auto acc = account_.lock()) if (auto convModule = acc->convModule(true)) { auto res = !convModule->isBanned(conversationId, cert->issuer->getId().toString()); res &= !convModule->isBanned(conversationId, cert->getLongId().toString()); return res; } return false; } void SwarmChannelHandler::onReady(const std::shared_ptr<dht::crypto::Certificate>&, const std::string& uri, std::shared_ptr<dhtnet::ChannelSocket> socket) { auto sep = uri.find_last_of('/'); auto conversationId = uri.substr(sep + 1); if (auto acc = account_.lock()) { if (auto convModule = acc->convModule(true)) { convModule->addSwarmChannel(conversationId, socket); } } } } // namespace jami
2,642
C++
.cpp
71
30.887324
95
0.655616
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,816
swarm_protocol.cpp
savoirfairelinux_jami-daemon/src/jamidht/swarm/swarm_protocol.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "swarm_protocol.h" #include <iostream> namespace jami { namespace swarm_protocol {}; // namespace swarm_protocol } // namespace jami
863
C++
.cpp
21
39.190476
73
0.75179
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,817
instant_messaging.cpp
savoirfairelinux_jami-daemon/src/im/instant_messaging.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "instant_messaging.h" #include "logger.h" #include "connectivity/sip_utils.h" #include <pjsip_ua.h> #include <pjsip.h> namespace jami { using sip_utils::CONST_PJ_STR; /** * the pair<string, string> we receive is expected to be in the format <mime type, payload> * the mime type is in the format "type/subtype" * in the header it will be presented as "Content-Type: type/subtype" * following the RFC spec, this header line can also contain other parameters in the format: * Content-Type: type/subtype; arg=value; arg=value; ... * thus we also accept the key of the map to be in such a format: * type/subtype; arg=value; arg=value; ... */ static void createMessageBody(pj_pool_t* pool, const std::pair<std::string, std::string>& payload, pjsip_msg_body** body_p) { /* parse the key: * 1. split by ';' * 2. parse the first result by spliting by '/' into a type and subtype * 3. parse any following strings into arg=value by splitting by '=' */ std::string_view mimeType, parameters; auto sep = payload.first.find(';'); if (std::string::npos == sep) { mimeType = payload.first; } else { mimeType = std::string_view(payload.first).substr(0, sep); parameters = std::string_view(payload.first).substr(sep + 1); } // split mime type to type and subtype sep = mimeType.find('/'); if (std::string::npos == sep) { JAMI_DBG("bad mime type: '%.*s'", (int) mimeType.size(), mimeType.data()); throw im::InstantMessageException("invalid mime type"); } auto type = sip_utils::CONST_PJ_STR(mimeType.substr(0, sep)); auto subtype = sip_utils::CONST_PJ_STR(mimeType.substr(sep + 1)); auto message = sip_utils::CONST_PJ_STR(payload.second); // create part *body_p = pjsip_msg_body_create(pool, &type, &subtype, &message); if (not parameters.size()) return; // now try to add parameters one by one do { sep = parameters.find(';'); auto paramPair = parameters.substr(0, sep); if (paramPair.empty()) break; // split paramPair into arg and value by '=' auto paramSplit = paramPair.find('='); if (std::string::npos == paramSplit) { JAMI_DBG("bad parameter: '%.*s'", (int) paramPair.size(), paramPair.data()); throw im::InstantMessageException("invalid parameter"); } auto arg = sip_utils::CONST_PJ_STR(paramPair.substr(0, paramSplit)); auto value = sip_utils::CONST_PJ_STR(paramPair.substr(paramSplit + 1)); pj_strtrim(&arg); pj_strtrim(&value); pj_str_t arg_pj, value_pj; pjsip_param* param = PJ_POOL_ALLOC_T(pool, pjsip_param); param->name = *pj_strdup(pool, &arg_pj, &arg); param->value = *pj_strdup(pool, &value_pj, &value); pj_list_push_back(&(*body_p)->content_type.param, param); // next parameter? if (std::string::npos != sep) parameters = parameters.substr(sep + 1); } while (std::string::npos != sep); } void im::fillPJSIPMessageBody(pjsip_tx_data& tdata, const std::map<std::string, std::string>& payloads) { // multi-part body? if (payloads.size() == 1) { createMessageBody(tdata.pool, *payloads.begin(), &tdata.msg->body); return; } /* if ctype is not specified "multipart/mixed" will be used * if the boundary is not specified, a random one will be generateAudioPort * FIXME: generate boundary and check that none of the message parts contain it before * calling this function; however the probability of this happenings if quite low as * the randomly generated string is fairly long */ tdata.msg->body = pjsip_multipart_create(tdata.pool, nullptr, nullptr); for (const auto& pair : payloads) { auto part = pjsip_multipart_create_part(tdata.pool); if (not part) { JAMI_ERR("pjsip_multipart_create_part failed: not enough memory"); throw InstantMessageException("Internal SIP error"); } createMessageBody(tdata.pool, pair, &part->body); auto status = pjsip_multipart_add_part(tdata.pool, tdata.msg->body, part); if (status != PJ_SUCCESS) { JAMI_ERR("pjsip_multipart_add_part failed: %s", sip_utils::sip_strerror(status).c_str()); throw InstantMessageException("Internal SIP error"); } } } void im::sendSipMessage(pjsip_inv_session* session, const std::map<std::string, std::string>& payloads) { if (payloads.empty()) { JAMI_WARN("the payloads argument is empty; ignoring message"); return; } constexpr pjsip_method msg_method = {PJSIP_OTHER_METHOD, CONST_PJ_STR(sip_utils::SIP_METHODS::MESSAGE)}; { auto dialog = session->dlg; sip_utils::PJDialogLock dialog_lock {dialog}; pjsip_tx_data* tdata = nullptr; auto status = pjsip_dlg_create_request(dialog, &msg_method, -1, &tdata); if (status != PJ_SUCCESS) { JAMI_ERR("pjsip_dlg_create_request failed: %s", sip_utils::sip_strerror(status).c_str()); throw InstantMessageException("Internal SIP error"); } fillPJSIPMessageBody(*tdata, payloads); status = pjsip_dlg_send_request(dialog, tdata, -1, nullptr); if (status != PJ_SUCCESS) { JAMI_ERR("pjsip_dlg_send_request failed: %s", sip_utils::sip_strerror(status).c_str()); throw InstantMessageException("Internal SIP error"); } } } /** * Creates std::pair with the Content-Type header contents as the first value and the message * payload as the second value. * * The format of the first value will be: * type/subtype[; *[; arg=value]] * eg: "text/plain;id=1234;part=2;of=1001" */ static std::pair<std::string, std::string> parseMessageBody(const pjsip_msg_body* body) { std::string header = sip_utils::as_view(body->content_type.type) + "/" + sip_utils::as_view(body->content_type.subtype); // iterate over parameters auto param = body->content_type.param.next; while (param != &body->content_type.param) { header += ";" + sip_utils::as_view(param->name) + "=" + sip_utils::as_view(param->value); param = param->next; } // get the payload, assume we can interpret it as chars return {std::move(header), std::string(static_cast<char*>(body->data), (size_t) body->len)}; } /** * Parses given SIP message into a map where the key is the contents of the Content-Type header * (along with any parameters) and the value is the message payload. * * @param msg received SIP message * * @return map of content types and message payloads */ std::map<std::string, std::string> im::parseSipMessage(const pjsip_msg* msg) { std::map<std::string, std::string> ret; if (!msg->body) { JAMI_WARN("message body is empty"); return ret; } // check if its a multipart message constexpr pj_str_t typeMultipart {CONST_PJ_STR("multipart")}; if (pj_strcmp(&typeMultipart, &msg->body->content_type.type) != 0) { // treat as single content type message ret.emplace(parseMessageBody(msg->body)); } else { /* multipart type message, we will treat it as multipart/mixed even if the subtype is * something else, eg: related */ auto part = pjsip_multipart_get_first_part(msg->body); while (part != nullptr) { ret.emplace(parseMessageBody(part->body)); part = pjsip_multipart_get_next_part(msg->body, part); } } return ret; } } // namespace jami
8,468
C++
.cpp
200
36.185
101
0.645537
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,818
message_engine.cpp
savoirfairelinux_jami-daemon/src/im/message_engine.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "message_engine.h" #include "sip/sipaccountbase.h" #include "manager.h" #include "fileutils.h" #include "client/ring_signal.h" #include "jami/account_const.h" #include <opendht/thread_pool.h> #include <fmt/std.h> #include <fstream> namespace jami { namespace im { MessageEngine::MessageEngine(SIPAccountBase& acc, const std::filesystem::path& path) : account_(acc) , savePath_(path) , ioContext_(Manager::instance().ioContext()) , saveTimer_(*ioContext_) { dhtnet::fileutils::check_dir(savePath_.parent_path()); } MessageToken MessageEngine::sendMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t refreshToken) { if (payloads.empty() or to.empty()) return 0; MessageToken token = 0; { std::lock_guard lock(messagesMutex_); auto& peerMessages = deviceId.empty() ? messages_[to] : messagesDevices_[deviceId]; if (refreshToken != 0) { for (auto& m : peerMessages) { if (m.token == refreshToken) { token = refreshToken; m.to = to; m.payloads = payloads; m.status = MessageStatus::IDLE; break; } } } if (token == 0) { token = std::uniform_int_distribution<MessageToken> {1, JAMI_ID_MAX_VAL}(account_.rand); auto& m = peerMessages.emplace_back(Message {token}); m.to = to; m.payloads = payloads; } scheduleSave(); } ioContext_->post([this, to, deviceId]() { retrySend(to, deviceId, true); }); return token; } void MessageEngine::onPeerOnline(const std::string& peer, const std::string& deviceId, bool retryOnTimeout) { retrySend(peer, deviceId, retryOnTimeout); } void MessageEngine::retrySend(const std::string& peer, const std::string& deviceId, bool retryOnTimeout) { if (account_.getRegistrationState() != RegistrationState::REGISTERED) return; struct PendingMsg { MessageToken token; std::string to; std::map<std::string, std::string> payloads; }; std::vector<PendingMsg> pending {}; auto now = clock::now(); { std::lock_guard lock(messagesMutex_); auto& m = deviceId.empty() ? messages_ : messagesDevices_; auto p = m.find(deviceId.empty() ? peer : deviceId); if (p == m.end()) return; auto& messages = p->second; for (auto& m: messages) { if (m.status == MessageStatus::IDLE) { m.status = MessageStatus::SENDING; m.retried++; m.last_op = now; pending.emplace_back(PendingMsg {m.token, m.to, m.payloads}); } } } // avoid locking while calling callback for (const auto& p : pending) { JAMI_DEBUG("[message {:d}] Reattempt sending", p.token); if (p.payloads.find("application/im-gitmessage-id") == p.payloads.end()) emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>( account_.getAccountID(), "", p.to, std::to_string(p.token), (int) libjami::Account::MessageStates::SENDING); account_.sendMessage(p.to, deviceId, p.payloads, p.token, retryOnTimeout, false); } } MessageStatus MessageEngine::getStatus(MessageToken t) const { std::lock_guard lock(messagesMutex_); for (const auto& p : messages_) { for (const auto& m : p.second) { if (m.token == t) return m.status; } } return MessageStatus::UNKNOWN; } void MessageEngine::onMessageSent(const std::string& peer, MessageToken token, bool ok, const std::string& deviceId) { JAMI_DEBUG("[message {:d}] Message sent: {:s}", token, ok ? "success"sv : "failure"sv); std::lock_guard lock(messagesMutex_); auto& m = deviceId.empty() ? messages_ : messagesDevices_; auto p = m.find(deviceId.empty() ? peer : deviceId); if (p == m.end()) { JAMI_WARNING("onMessageSent: Peer not found: id:{} device:{}", peer, deviceId); return; } auto f = std::find_if(p->second.begin(), p->second.end(), [&](const Message& m) { return m.token == token; }); if (f != p->second.end()) { auto emit = f->payloads.find("application/im-gitmessage-id") == f->payloads.end(); if (f->status == MessageStatus::SENDING) { if (ok) { f->status = MessageStatus::SENT; JAMI_LOG("[message {:d}] Status changed to SENT", token); if (emit) emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>( account_.getAccountID(), "", f->to, std::to_string(token), static_cast<int>(libjami::Account::MessageStates::SENT)); p->second.erase(f); scheduleSave(); } else if (f->retried >= MAX_RETRIES) { f->status = MessageStatus::FAILURE; JAMI_WARNING("[message {:d}] Status changed to FAILURE", token); if (emit) emitSignal<libjami::ConfigurationSignal::AccountMessageStatusChanged>( account_.getAccountID(), "", f->to, std::to_string(token), static_cast<int>(libjami::Account::MessageStates::FAILURE)); p->second.erase(f); scheduleSave(); } else { f->status = MessageStatus::IDLE; JAMI_DEBUG("[message {:d}] Status changed to IDLE", token); } } else { JAMI_DEBUG("[message {:d}] State is not SENDING", token); } } else { JAMI_DEBUG("[message {:d}] Unable to find message", token); } } void MessageEngine::load() { try { decltype(messages_) root; { std::lock_guard lock(dhtnet::fileutils::getFileLock(savePath_)); std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); file.open(savePath_); if (file.is_open()) { msgpack::unpacker up; up.reserve_buffer(UINT16_MAX); while (file.read(up.buffer(), UINT16_MAX)) { up.buffer_consumed(file.gcount()); msgpack::object_handle oh; if (up.next(oh)) { root = oh.get().as<std::map<std::string, std::list<Message>>>(); break; } up.reserve_buffer(UINT16_MAX); } } } std::lock_guard lock(messagesMutex_); messages_ = std::move(root); if (not messages_.empty()) { JAMI_LOG("[Account {}] Loaded {} messages from {}", account_.getAccountID(), messages_.size(), savePath_); } } catch (const std::exception& e) { JAMI_LOG("[Account {}] Unable to load messages from {}: {}", account_.getAccountID(), savePath_, e.what()); } } void MessageEngine::save() const { std::lock_guard lock(messagesMutex_); save_(); } void MessageEngine::scheduleSave() { saveTimer_.expires_after(std::chrono::seconds(5)); saveTimer_.async_wait([this, w = account_.weak_from_this()](const std::error_code& ec) { if (!ec) if (auto acc = w.lock()) save(); }); } void MessageEngine::save_() const { try { std::ofstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); file.open(savePath_, std::ios::trunc); if (file.is_open()) msgpack::pack(file, messages_); } catch (const std::exception& e) { JAMI_ERROR("[Account {}] Unable to serialize pending messages: {}", account_.getAccountID(), e.what()); } } } // namespace im } // namespace jami
9,262
C++
.cpp
256
26.347656
100
0.549905
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,819
webviewservicesmanager.cpp
savoirfairelinux_jami-daemon/src/plugin/webviewservicesmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "webviewservicesmanager.h" #include "client/ring_signal.h" #include "pluginmanager.h" #include "logger.h" #include "manager.h" #include "jamidht/jamiaccount.h" #include "fileutils.h" #include "plugin_manager_interface.h" #include "pluginsutils.h" #include "webviewmessage.h" #include <cstdint> #include <vector> namespace jami { WebViewServicesManager::WebViewServicesManager(PluginManager& pluginManager) { registerComponentsLifeCycleManagers(pluginManager); registerWebViewService(pluginManager); } WebViewHandler* WebViewServicesManager::getWebViewHandlerPointer(const std::string& pluginId) { auto it = handlersIdMap.find(pluginId); // check if handler with specified pluginId does not exist if (it == handlersIdMap.end()) { JAMI_ERR("handler with pluginId %s was not found!", pluginId.c_str()); return nullptr; } // we know that the pointer exists return it->second.get(); } void WebViewServicesManager::registerComponentsLifeCycleManagers(PluginManager& pluginManager) { // called by the plugin manager whenever a plugin is loaded auto registerWebViewHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); WebViewHandlerPtr ptr {(static_cast<WebViewHandler*>(data))}; // make sure pointer is valid if (!ptr) { JAMI_ERR("Attempting to register a webview handler with invalid pointer!"); return -1; } // pointer is valid, get details auto id = ptr->id(); // add the handler to our map handlersIdMap[id] = std::move(ptr); return 0; }; // called by the plugin manager whenever a plugin is unloaded auto unregisterWebViewHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard pluginManagerLock(pmMtx_); WebViewHandler* ptr {(static_cast<WebViewHandler*>(data))}; // make sure pointer is valid if (!ptr) { JAMI_ERR("Attempting to unregister a webview handler with invalid pointer!"); return false; } // pointer is valid, get details auto id = ptr->id(); // remove from our map, unique_ptr gets destroyed handlersIdMap.erase(id); return true; }; // register the functions pluginManager.registerComponentManager("WebViewHandlerManager", registerWebViewHandler, unregisterWebViewHandler); } void WebViewServicesManager::registerWebViewService(PluginManager& pluginManager) { // NOTE: These are API calls that can be called by the plugin auto pluginWebViewMessage = [](const DLPlugin* plugin, void* data) { // the plugin must pass data as a WebViewMessage pointer auto* message = static_cast<WebViewMessage*>(data); // get datapath for the plugin std::string dataPath = PluginUtils::dataPath(plugin->getPath()).string(); emitSignal<libjami::PluginSignal::WebViewMessageReceived>(dataPath, message->webViewId, message->messageId, message->payload); return 0; }; // register the service. pluginManager.registerService("pluginWebViewMessage", pluginWebViewMessage); } void WebViewServicesManager::sendWebViewMessage(const std::string& pluginId, const std::string& webViewId, const std::string& messageId, const std::string& payload) { if (auto* handler = getWebViewHandlerPointer(pluginId)) { handler->pluginWebViewMessage(webViewId, messageId, payload); } } std::string WebViewServicesManager::sendWebViewAttach(const std::string& pluginId, const std::string& accountId, const std::string& webViewId, const std::string& action) { if (auto* handler = getWebViewHandlerPointer(pluginId)) { return handler->pluginWebViewAttach(accountId, webViewId, action); } return ""; } void WebViewServicesManager::sendWebViewDetach(const std::string& pluginId, const std::string& webViewId) { if (auto* handler = getWebViewHandlerPointer(pluginId)) { handler->pluginWebViewDetach(webViewId); } } } // namespace jami
5,325
C++
.cpp
131
32.145038
100
0.648152
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,820
store_ca_crt.cpp
savoirfairelinux_jami-daemon/src/plugin/store_ca_crt.cpp
unsigned char store_ca_crt[] = { 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x0a, 0x4d, 0x49, 0x49, 0x43, 0x55, 0x7a, 0x43, 0x43, 0x41, 0x66, 0x71, 0x67, 0x41, 0x77, 0x49, 0x42, 0x41, 0x67, 0x49, 0x55, 0x51, 0x6b, 0x5a, 0x64, 0x75, 0x5a, 0x57, 0x42, 0x6a, 0x58, 0x73, 0x57, 0x48, 0x33, 0x4d, 0x48, 0x4c, 0x47, 0x63, 0x41, 0x56, 0x65, 0x33, 0x30, 0x4f, 0x72, 0x38, 0x77, 0x43, 0x67, 0x59, 0x49, 0x4b, 0x6f, 0x5a, 0x49, 0x7a, 0x6a, 0x30, 0x45, 0x41, 0x77, 0x49, 0x77, 0x0a, 0x67, 0x59, 0x55, 0x78, 0x49, 0x54, 0x41, 0x66, 0x42, 0x67, 0x4e, 0x56, 0x42, 0x41, 0x4d, 0x4d, 0x47, 0x45, 0x70, 0x68, 0x62, 0x57, 0x6b, 0x67, 0x52, 0x58, 0x68, 0x30, 0x5a, 0x57, 0x35, 0x7a, 0x61, 0x57, 0x39, 0x75, 0x49, 0x46, 0x4a, 0x76, 0x62, 0x33, 0x51, 0x67, 0x51, 0x79, 0x35, 0x42, 0x4c, 0x6a, 0x45, 0x4c, 0x4d, 0x41, 0x6b, 0x47, 0x41, 0x31, 0x55, 0x45, 0x42, 0x68, 0x4d, 0x43, 0x0a, 0x51, 0x30, 0x45, 0x78, 0x44, 0x7a, 0x41, 0x4e, 0x42, 0x67, 0x4e, 0x56, 0x42, 0x41, 0x67, 0x4d, 0x42, 0x6c, 0x46, 0x31, 0x5a, 0x57, 0x4a, 0x6c, 0x59, 0x7a, 0x45, 0x52, 0x4d, 0x41, 0x38, 0x47, 0x41, 0x31, 0x55, 0x45, 0x42, 0x77, 0x77, 0x49, 0x54, 0x57, 0x39, 0x75, 0x64, 0x48, 0x4a, 0x6c, 0x59, 0x57, 0x77, 0x78, 0x49, 0x44, 0x41, 0x65, 0x42, 0x67, 0x4e, 0x56, 0x42, 0x41, 0x6f, 0x4d, 0x0a, 0x46, 0x31, 0x4e, 0x68, 0x64, 0x6d, 0x39, 0x70, 0x63, 0x69, 0x31, 0x6d, 0x59, 0x57, 0x6c, 0x79, 0x5a, 0x53, 0x42, 0x4d, 0x61, 0x57, 0x35, 0x31, 0x65, 0x43, 0x42, 0x4a, 0x62, 0x6d, 0x4d, 0x75, 0x4d, 0x51, 0x30, 0x77, 0x43, 0x77, 0x59, 0x44, 0x56, 0x51, 0x51, 0x4c, 0x44, 0x41, 0x52, 0x4b, 0x59, 0x57, 0x31, 0x70, 0x4d, 0x43, 0x41, 0x58, 0x44, 0x54, 0x49, 0x7a, 0x4d, 0x54, 0x49, 0x78, 0x0a, 0x4e, 0x7a, 0x45, 0x32, 0x4e, 0x54, 0x63, 0x30, 0x4e, 0x46, 0x6f, 0x59, 0x44, 0x7a, 0x49, 0x77, 0x4e, 0x54, 0x4d, 0x78, 0x4d, 0x6a, 0x41, 0x35, 0x4d, 0x54, 0x59, 0x31, 0x4e, 0x7a, 0x51, 0x30, 0x57, 0x6a, 0x43, 0x42, 0x68, 0x54, 0x45, 0x68, 0x4d, 0x42, 0x38, 0x47, 0x41, 0x31, 0x55, 0x45, 0x41, 0x77, 0x77, 0x59, 0x53, 0x6d, 0x46, 0x74, 0x61, 0x53, 0x42, 0x46, 0x65, 0x48, 0x52, 0x6c, 0x0a, 0x62, 0x6e, 0x4e, 0x70, 0x62, 0x32, 0x34, 0x67, 0x55, 0x6d, 0x39, 0x76, 0x64, 0x43, 0x42, 0x44, 0x4c, 0x6b, 0x45, 0x75, 0x4d, 0x51, 0x73, 0x77, 0x43, 0x51, 0x59, 0x44, 0x56, 0x51, 0x51, 0x47, 0x45, 0x77, 0x4a, 0x44, 0x51, 0x54, 0x45, 0x50, 0x4d, 0x41, 0x30, 0x47, 0x41, 0x31, 0x55, 0x45, 0x43, 0x41, 0x77, 0x47, 0x55, 0x58, 0x56, 0x6c, 0x59, 0x6d, 0x56, 0x6a, 0x4d, 0x52, 0x45, 0x77, 0x0a, 0x44, 0x77, 0x59, 0x44, 0x56, 0x51, 0x51, 0x48, 0x44, 0x41, 0x68, 0x4e, 0x62, 0x32, 0x35, 0x30, 0x63, 0x6d, 0x56, 0x68, 0x62, 0x44, 0x45, 0x67, 0x4d, 0x42, 0x34, 0x47, 0x41, 0x31, 0x55, 0x45, 0x43, 0x67, 0x77, 0x58, 0x55, 0x32, 0x46, 0x32, 0x62, 0x32, 0x6c, 0x79, 0x4c, 0x57, 0x5a, 0x68, 0x61, 0x58, 0x4a, 0x6c, 0x49, 0x45, 0x78, 0x70, 0x62, 0x6e, 0x56, 0x34, 0x49, 0x45, 0x6c, 0x75, 0x0a, 0x59, 0x79, 0x34, 0x78, 0x44, 0x54, 0x41, 0x4c, 0x42, 0x67, 0x4e, 0x56, 0x42, 0x41, 0x73, 0x4d, 0x42, 0x45, 0x70, 0x68, 0x62, 0x57, 0x6b, 0x77, 0x57, 0x54, 0x41, 0x54, 0x42, 0x67, 0x63, 0x71, 0x68, 0x6b, 0x6a, 0x4f, 0x50, 0x51, 0x49, 0x42, 0x42, 0x67, 0x67, 0x71, 0x68, 0x6b, 0x6a, 0x4f, 0x50, 0x51, 0x4d, 0x42, 0x42, 0x77, 0x4e, 0x43, 0x41, 0x41, 0x54, 0x2b, 0x43, 0x41, 0x63, 0x74, 0x0a, 0x59, 0x76, 0x72, 0x4f, 0x54, 0x4a, 0x32, 0x4f, 0x42, 0x6c, 0x57, 0x35, 0x55, 0x79, 0x67, 0x74, 0x61, 0x67, 0x48, 0x41, 0x70, 0x74, 0x77, 0x50, 0x2f, 0x6e, 0x7a, 0x53, 0x77, 0x67, 0x46, 0x4e, 0x4e, 0x56, 0x48, 0x57, 0x69, 0x59, 0x6c, 0x64, 0x34, 0x7a, 0x74, 0x33, 0x51, 0x6e, 0x73, 0x47, 0x4c, 0x49, 0x55, 0x33, 0x49, 0x6f, 0x78, 0x59, 0x4e, 0x50, 0x68, 0x32, 0x36, 0x75, 0x5a, 0x50, 0x0a, 0x69, 0x36, 0x59, 0x57, 0x44, 0x45, 0x64, 0x31, 0x4b, 0x78, 0x39, 0x42, 0x6f, 0x39, 0x63, 0x74, 0x6f, 0x30, 0x51, 0x77, 0x51, 0x6a, 0x41, 0x79, 0x42, 0x67, 0x4e, 0x56, 0x48, 0x52, 0x38, 0x45, 0x4b, 0x7a, 0x41, 0x70, 0x4d, 0x43, 0x65, 0x67, 0x4a, 0x61, 0x41, 0x6a, 0x68, 0x69, 0x46, 0x6f, 0x64, 0x48, 0x52, 0x77, 0x63, 0x7a, 0x6f, 0x76, 0x4c, 0x33, 0x42, 0x73, 0x64, 0x57, 0x64, 0x70, 0x0a, 0x62, 0x6e, 0x4d, 0x75, 0x61, 0x6d, 0x46, 0x74, 0x61, 0x53, 0x35, 0x75, 0x5a, 0x58, 0x51, 0x76, 0x59, 0x33, 0x4a, 0x73, 0x4c, 0x33, 0x4a, 0x76, 0x62, 0x33, 0x51, 0x77, 0x44, 0x41, 0x59, 0x44, 0x56, 0x52, 0x30, 0x54, 0x42, 0x41, 0x55, 0x77, 0x41, 0x77, 0x45, 0x42, 0x2f, 0x7a, 0x41, 0x4b, 0x42, 0x67, 0x67, 0x71, 0x68, 0x6b, 0x6a, 0x4f, 0x50, 0x51, 0x51, 0x44, 0x41, 0x67, 0x4e, 0x48, 0x0a, 0x41, 0x44, 0x42, 0x45, 0x41, 0x69, 0x41, 0x76, 0x53, 0x35, 0x4c, 0x72, 0x6a, 0x6c, 0x74, 0x44, 0x38, 0x37, 0x4b, 0x72, 0x31, 0x55, 0x49, 0x36, 0x54, 0x35, 0x57, 0x51, 0x44, 0x46, 0x72, 0x4e, 0x72, 0x2b, 0x46, 0x4c, 0x49, 0x76, 0x6c, 0x57, 0x52, 0x43, 0x54, 0x43, 0x58, 0x61, 0x49, 0x47, 0x42, 0x51, 0x49, 0x67, 0x63, 0x44, 0x4f, 0x35, 0x58, 0x4d, 0x43, 0x45, 0x61, 0x78, 0x68, 0x72, 0x0a, 0x72, 0x32, 0x79, 0x56, 0x69, 0x77, 0x54, 0x6c, 0x38, 0x55, 0x62, 0x58, 0x45, 0x31, 0x45, 0x5a, 0x52, 0x48, 0x49, 0x46, 0x4c, 0x67, 0x39, 0x38, 0x4e, 0x67, 0x7a, 0x43, 0x4d, 0x6c, 0x59, 0x3d, 0x0a, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d };
5,376
C++
.cpp
75
68.746667
73
0.657488
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,821
chatservicesmanager.cpp
savoirfairelinux_jami-daemon/src/plugin/chatservicesmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "chatservicesmanager.h" #include "pluginmanager.h" #include "logger.h" #include "manager.h" #include "jamidht/jamiaccount.h" #include "fileutils.h" namespace jami { ChatServicesManager::ChatServicesManager(PluginManager& pluginManager) { registerComponentsLifeCycleManagers(pluginManager); registerChatService(pluginManager); PluginPreferencesUtils::getAllowDenyListPreferences(allowDenyList_); } void ChatServicesManager::registerComponentsLifeCycleManagers(PluginManager& pluginManager) { // registerChatHandler may be called by the PluginManager upon loading a plugin. auto registerChatHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); ChatHandlerPtr ptr {(static_cast<ChatHandler*>(data))}; if (!ptr) return -1; handlersNameMap_[ptr->getChatHandlerDetails().at("name")] = (uintptr_t) ptr.get(); std::size_t found = ptr->id().find_last_of(DIR_SEPARATOR_CH); // Adding preference that tells us to automatically activate a ChatHandler. PluginPreferencesUtils::addAlwaysHandlerPreference(ptr->getChatHandlerDetails().at("name"), ptr->id().substr(0, found)); chatHandlers_.emplace_back(std::move(ptr)); return 0; }; // unregisterChatHandler may be called by the PluginManager while unloading. auto unregisterChatHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); auto handlerIt = std::find_if(chatHandlers_.begin(), chatHandlers_.end(), [data](ChatHandlerPtr& handler) { return (handler.get() == data); }); if (handlerIt != chatHandlers_.end()) { for (auto& toggledList : chatHandlerToggled_) { auto handlerId = std::find_if(toggledList.second.begin(), toggledList.second.end(), [id = (uintptr_t) handlerIt->get()]( uintptr_t handlerId) { return (handlerId == id); }); // If ChatHandler is attempting to destroy one which is currently in use, we deactivate it. if (handlerId != toggledList.second.end()) { (*handlerIt)->detach(chatSubjects_[toggledList.first]); toggledList.second.erase(handlerId); } } handlersNameMap_.erase((*handlerIt)->getChatHandlerDetails().at("name")); chatHandlers_.erase(handlerIt); } return true; }; // Services are registered to the PluginManager. pluginManager.registerComponentManager("ChatHandlerManager", registerChatHandler, unregisterChatHandler); } void ChatServicesManager::registerChatService(PluginManager& pluginManager) { // sendTextMessage is a service that allows plugins to send a message in a conversation. auto sendTextMessage = [](const DLPlugin*, void* data) { auto cm = static_cast<JamiMessage*>(data); if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>( cm->accountId)) { try { if (cm->isSwarm) acc->convModule()->sendMessage(cm->peerId, cm->data.at("body")); else jami::Manager::instance().sendTextMessage(cm->accountId, cm->peerId, cm->data, true); } catch (const std::exception& e) { JAMI_ERR("Exception during text message sending: %s", e.what()); } } return 0; }; // Services are registered to the PluginManager. pluginManager.registerService("sendTextMessage", sendTextMessage); } bool ChatServicesManager::hasHandlers() const { return not chatHandlers_.empty(); } std::vector<std::string> ChatServicesManager::getChatHandlers() const { std::vector<std::string> res; res.reserve(chatHandlers_.size()); for (const auto& chatHandler : chatHandlers_) { res.emplace_back(std::to_string((uintptr_t) chatHandler.get())); } return res; } void ChatServicesManager::publishMessage(pluginMessagePtr message) { if (message->fromPlugin or chatHandlers_.empty()) return; std::pair<std::string, std::string> mPair(message->accountId, message->peerId); auto& handlers = chatHandlerToggled_[mPair]; auto& chatAllowDenySet = allowDenyList_[mPair]; // Search for activation flag. for (auto& chatHandler : chatHandlers_) { std::string chatHandlerName = chatHandler->getChatHandlerDetails().at("name"); std::size_t found = chatHandler->id().find_last_of(DIR_SEPARATOR_CH); // toggle is true if we should automatically activate the ChatHandler. bool toggle = PluginPreferencesUtils::getAlwaysPreference(chatHandler->id().substr(0, found), chatHandlerName, message->accountId); // toggle is overwritten if we have previously activated/deactivated the ChatHandler // for the given conversation. auto allowedIt = chatAllowDenySet.find(chatHandlerName); if (allowedIt != chatAllowDenySet.end()) toggle = (*allowedIt).second; bool toggled = handlers.find((uintptr_t) chatHandler.get()) != handlers.end(); if (toggle || toggled) { // Creates chat subjects if it doesn't exist yet. auto& subject = chatSubjects_.emplace(mPair, std::make_shared<PublishObservable<pluginMessagePtr>>()).first->second; if (!toggled) { // If activation is expected, and not yet performed, we perform activation handlers.insert((uintptr_t) chatHandler.get()); chatHandler->notifyChatSubject(mPair, subject); chatAllowDenySet[chatHandlerName] = true; PluginPreferencesUtils::setAllowDenyListPreferences(allowDenyList_); } // Finally we feed Chat subject with the message. subject->publish(message); } } } void ChatServicesManager::cleanChatSubjects(const std::string& accountId, const std::string& peerId) { std::pair<std::string, std::string> mPair(accountId, peerId); for (auto it = chatSubjects_.begin(); it != chatSubjects_.end();) { if (peerId.empty() && it->first.first == accountId) it = chatSubjects_.erase(it); else if (!peerId.empty() && it->first == mPair) it = chatSubjects_.erase(it); else ++it; } } void ChatServicesManager::toggleChatHandler(const std::string& chatHandlerId, const std::string& accountId, const std::string& peerId, const bool toggle) { toggleChatHandler(std::stoull(chatHandlerId), accountId, peerId, toggle); } std::vector<std::string> ChatServicesManager::getChatHandlerStatus(const std::string& accountId, const std::string& peerId) { std::pair<std::string, std::string> mPair(accountId, peerId); const auto& it = allowDenyList_.find(mPair); std::vector<std::string> ret; if (it != allowDenyList_.end()) { for (const auto& chatHandlerName : it->second) if (chatHandlerName.second && handlersNameMap_.find(chatHandlerName.first) != handlersNameMap_.end()) { // We only return active ChatHandler ids ret.emplace_back(std::to_string(handlersNameMap_.at(chatHandlerName.first))); } } return ret; } std::map<std::string, std::string> ChatServicesManager::getChatHandlerDetails(const std::string& chatHandlerIdStr) { auto chatHandlerId = std::stoull(chatHandlerIdStr); for (auto& chatHandler : chatHandlers_) { if ((uintptr_t) chatHandler.get() == chatHandlerId) { return chatHandler->getChatHandlerDetails(); } } return {}; } bool ChatServicesManager::setPreference(const std::string& key, const std::string& value, const std::string& rootPath) { bool status {true}; for (auto& chatHandler : chatHandlers_) { if (chatHandler->id().find(rootPath) != std::string::npos) { if (chatHandler->preferenceMapHasKey(key)) { chatHandler->setPreferenceAttribute(key, value); status &= false; } } } return status; } void ChatServicesManager::toggleChatHandler(const uintptr_t chatHandlerId, const std::string& accountId, const std::string& peerId, const bool toggle) { std::pair<std::string, std::string> mPair(accountId, peerId); auto& handlers = chatHandlerToggled_[mPair]; auto& chatAllowDenySet = allowDenyList_[mPair]; chatSubjects_.emplace(mPair, std::make_shared<PublishObservable<pluginMessagePtr>>()); auto chatHandlerIt = std::find_if(chatHandlers_.begin(), chatHandlers_.end(), [chatHandlerId](ChatHandlerPtr& handler) { return ((uintptr_t) handler.get() == chatHandlerId); }); if (chatHandlerIt != chatHandlers_.end()) { if (toggle) { (*chatHandlerIt)->notifyChatSubject(mPair, chatSubjects_[mPair]); if (handlers.find(chatHandlerId) == handlers.end()) handlers.insert(chatHandlerId); chatAllowDenySet[(*chatHandlerIt)->getChatHandlerDetails().at("name")] = true; } else { (*chatHandlerIt)->detach(chatSubjects_[mPair]); handlers.erase(chatHandlerId); chatAllowDenySet[(*chatHandlerIt)->getChatHandlerDetails().at("name")] = false; } PluginPreferencesUtils::setAllowDenyListPreferences(allowDenyList_); } } } // namespace jami
11,372
C++
.cpp
247
34.445344
156
0.597297
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,822
preferenceservicesmanager.cpp
savoirfairelinux_jami-daemon/src/plugin/preferenceservicesmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "preferenceservicesmanager.h" #include "pluginmanager.h" #include "pluginpreferencesutils.h" #include "manager.h" #include "sip/sipcall.h" #include "fileutils.h" #include "logger.h" namespace jami { PreferenceServicesManager::PreferenceServicesManager(PluginManager& pluginManager) { registerComponentsLifeCycleManagers(pluginManager); } PreferenceServicesManager::~PreferenceServicesManager() { handlers_.clear(); } std::vector<std::string> PreferenceServicesManager::getHandlers() const { std::vector<std::string> res; res.reserve(handlers_.size()); for (const auto& preferenceHandler : handlers_) { res.emplace_back(std::to_string((uintptr_t) preferenceHandler.get())); } return res; } std::map<std::string, std::string> PreferenceServicesManager::getHandlerDetails(const std::string& preferenceHandlerIdStr) const { auto preferenceHandlerId = std::stoull(preferenceHandlerIdStr); for (auto& preferenceHandler : handlers_) { if ((uintptr_t) preferenceHandler.get() == preferenceHandlerId) { return preferenceHandler->getHandlerDetails(); } } return {}; } bool PreferenceServicesManager::setPreference(const std::string& key, const std::string& value, const std::string& rootPath, const std::string& accountId) { bool status {true}; for (auto& preferenceHandler : handlers_) { if (preferenceHandler->id().find(rootPath) != std::string::npos) { if (preferenceHandler->preferenceMapHasKey(key)) { preferenceHandler->setPreferenceAttribute(accountId, key, value); // We can return here since we expect plugins to have a single preferencehandler return false; } } } return status; } void PreferenceServicesManager::resetPreferences(const std::string& rootPath, const std::string& accountId) { for (auto& preferenceHandler : handlers_) { if (preferenceHandler->id().find(rootPath) != std::string::npos) { preferenceHandler->resetPreferenceAttributes(accountId); } } } void PreferenceServicesManager::registerComponentsLifeCycleManagers(PluginManager& pluginManager) { // registerHandler may be called by the PluginManager upon loading a plugin. auto registerHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); PreferenceHandlerPtr ptr {(static_cast<PreferenceHandler*>(data))}; if (!ptr) return -1; handlers_.emplace_back(std::move(ptr)); return 0; }; // unregisterHandler may be called by the PluginManager while unloading. auto unregisterHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); auto handlerIt = std::find_if(handlers_.begin(), handlers_.end(), [data](PreferenceHandlerPtr& handler) { return (handler.get() == data); }); if (handlerIt != handlers_.end()) { handlers_.erase(handlerIt); } return true; }; // Services are registered to the PluginManager. pluginManager.registerComponentManager("PreferenceHandlerManager", registerHandler, unregisterHandler); } } // namespace jami
4,348
C++
.cpp
112
30.723214
96
0.643923
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,823
jamipluginmanager.cpp
savoirfairelinux_jami-daemon/src/plugin/jamipluginmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "jamipluginmanager.h" #include "pluginsutils.h" #include "fileutils.h" #include "archiver.h" #include "logger.h" #include "manager.h" #include "jami/plugin_manager_interface.h" #include "store_ca_crt.cpp" #include <fstream> #include <stdexcept> #include <msgpack.hpp> #define FAILURE -1 #define SUCCESS 0 #define PLUGIN_ALREADY_INSTALLED 100 /* Plugin already installed with the same version */ #define PLUGIN_OLD_VERSION 200 /* Plugin already installed with a newer version */ #define SIGNATURE_VERIFICATION_FAILED 300 #define CERTIFICATE_VERIFICATION_FAILED 400 #define INVALID_PLUGIN 500 #ifdef WIN32 #define LIB_TYPE ".dll" #define LIB_PREFIX "" #else #ifdef __APPLE__ #define LIB_TYPE ".dylib" #define LIB_PREFIX "lib" #else #define LIB_TYPE ".so" #define LIB_PREFIX "lib" #endif #endif namespace jami { JamiPluginManager::JamiPluginManager() : callsm_ {pm_} , chatsm_ {pm_} , webviewsm_ {pm_} , preferencesm_ {pm_} { registerServices(); } std::string JamiPluginManager::getPluginAuthor(const std::string& rootPath, const std::string& pluginId) { auto cert = PluginUtils::readPluginCertificate(rootPath, pluginId); if (!cert) { JAMI_ERROR("Unable to read plugin certificate"); return {}; } return cert->getIssuerName(); } std::map<std::string, std::string> JamiPluginManager::getPluginDetails(const std::string& rootPath, bool reset) { auto detailsIt = pluginDetailsMap_.find(rootPath); if (detailsIt != pluginDetailsMap_.end()) { if (!reset) return detailsIt->second; pluginDetailsMap_.erase(detailsIt); } std::map<std::string, std::string> details = PluginUtils::parseManifestFile( PluginUtils::manifestPath(rootPath), rootPath); if (!details.empty()) { auto itIcon = details.find("iconPath"); itIcon->second.insert(0, rootPath + DIR_SEPARATOR_CH + "data" + DIR_SEPARATOR_CH); auto itImage = details.find("backgroundPath"); itImage->second.insert(0, rootPath + DIR_SEPARATOR_CH + "data" + DIR_SEPARATOR_CH); details["soPath"] = rootPath + DIR_SEPARATOR_CH + LIB_PREFIX + details["id"] + LIB_TYPE; details["author"] = getPluginAuthor(rootPath, details["id"]); detailsIt = pluginDetailsMap_.emplace(rootPath, std::move(details)).first; return detailsIt->second; } return {}; } std::vector<std::string> JamiPluginManager::getInstalledPlugins() { // Gets all plugins in standard path auto pluginsPath = fileutils::get_data_dir() / "plugins"; std::vector<std::string> pluginsPaths; std::error_code ec; for (const auto& entry : std::filesystem::directory_iterator(pluginsPath, ec)) { const auto& p = entry.path(); if (PluginUtils::checkPluginValidity(p)) pluginsPaths.emplace_back(p.string()); } // Gets plugins installed in non standard path std::vector<std::string> nonStandardInstalls = jami::Manager::instance() .pluginPreferences.getInstalledPlugins(); for (auto& path : nonStandardInstalls) { if (PluginUtils::checkPluginValidity(path)) pluginsPaths.emplace_back(path); } return pluginsPaths; } bool JamiPluginManager::checkPluginCertificatePublicKey(const std::string& oldJplPath, const std::string& newJplPath) { std::map<std::string, std::string> oldDetails = PluginUtils::parseManifestFile(PluginUtils::manifestPath(oldJplPath), oldJplPath); if ( oldDetails.empty() || !std::filesystem::is_regular_file(oldJplPath + DIR_SEPARATOR_CH + oldDetails["id"] + ".crt") || !std::filesystem::is_regular_file(newJplPath) ) return false; try { auto oldCert = PluginUtils::readPluginCertificate(oldJplPath, oldDetails["id"]); auto newCert = PluginUtils::readPluginCertificateFromArchive(newJplPath); if (!oldCert || !newCert) { return false; } return oldCert->getPublicKey() == newCert->getPublicKey(); } catch (const std::exception& e) { JAMI_ERR() << e.what(); return false; } return true; } bool JamiPluginManager::checkPluginCertificateValidity(dht::crypto::Certificate* cert) { trust_.add(crypto::Certificate(store_ca_crt, sizeof(store_ca_crt))); return cert && *cert && trust_.verify(*cert); } std::map<std::string, std::string> JamiPluginManager::getPlatformInfo() { return PluginUtils::getPlatformInfo(); } bool JamiPluginManager::checkPluginSignatureFile(const std::string& jplPath) { // check if the file exists if (!std::filesystem::is_regular_file(jplPath)){ return false; } try { auto signatures = PluginUtils::readPluginSignatureFromArchive(jplPath); auto manifest = PluginUtils::readPluginManifestFromArchive(jplPath); const std::string& name = manifest["id"]; auto filesPath = archiver::listFilesFromArchive(jplPath); for (const auto& file : filesPath) { // we skip the signatures and signatures.sig file if (file == "signatures" || file == "signatures.sig") continue; // we also skip the plugin certificate if (file == name + ".crt") continue; if (signatures.count(file) == 0) { return false; } } } catch (const std::exception& e) { return false; } return true; } bool JamiPluginManager::checkPluginSignatureValidity(const std::string& jplPath, dht::crypto::Certificate* cert) { if (!std::filesystem::is_regular_file(jplPath)) return false; try{ const auto& pk = cert->getPublicKey(); auto signaturesData = archiver::readFileFromArchive(jplPath, "signatures"); auto signatureFile = PluginUtils::readSignatureFileFromArchive(jplPath); if (!pk.checkSignature(signaturesData, signatureFile)) return false; auto signatures = PluginUtils::readPluginSignatureFromArchive(jplPath); for (const auto& signature : signatures) { auto file = archiver::readFileFromArchive(jplPath, signature.first); if (!pk.checkSignature(file, signature.second)){ JAMI_ERROR("{} not correctly signed", signature.first); return false; } } } catch (const std::exception& e) { return false; } return true; } bool JamiPluginManager::checkPluginSignature(const std::string& jplPath, dht::crypto::Certificate* cert) { if (!std::filesystem::is_regular_file(jplPath) || !cert || !*cert) return false; try { return checkPluginSignatureValidity(jplPath, cert) && checkPluginSignatureFile(jplPath); } catch (const std::exception& e) { return false; } } std::unique_ptr<dht::crypto::Certificate> JamiPluginManager::checkPluginCertificate(const std::string& jplPath, bool force) { if (!std::filesystem::is_regular_file(jplPath)) return {}; try { auto cert = PluginUtils::readPluginCertificateFromArchive(jplPath); if(checkPluginCertificateValidity(cert.get()) || force){ return cert; } return {}; } catch (const std::exception& e) { return {}; } } int JamiPluginManager::installPlugin(const std::string& jplPath, bool force) { int r {SUCCESS}; if (std::filesystem::is_regular_file(jplPath)) { try { auto manifestMap = PluginUtils::readPluginManifestFromArchive(jplPath); const std::string& name = manifestMap["id"]; if (name.empty()) return INVALID_PLUGIN; auto cert = checkPluginCertificate(jplPath, force); if (!cert) return CERTIFICATE_VERIFICATION_FAILED; if(!checkPluginSignature(jplPath, cert.get())) return SIGNATURE_VERIFICATION_FAILED; const std::string& version = manifestMap["version"]; auto destinationDir = (fileutils::get_data_dir() / "plugins" / name).string(); // Find if there is an existing version of this plugin const auto alreadyInstalledManifestMap = PluginUtils::parseManifestFile( PluginUtils::manifestPath(destinationDir), destinationDir); if (!alreadyInstalledManifestMap.empty()) { if (force) { r = uninstallPlugin(destinationDir); if (r == SUCCESS) { archiver::uncompressArchive(jplPath, destinationDir, PluginUtils::uncompressJplFunction); } } else { std::string installedVersion = alreadyInstalledManifestMap.at("version"); if (version > installedVersion) { if(!checkPluginCertificatePublicKey(destinationDir, jplPath)) return CERTIFICATE_VERIFICATION_FAILED; r = uninstallPlugin(destinationDir); if (r == SUCCESS) { archiver::uncompressArchive(jplPath, destinationDir, PluginUtils::uncompressJplFunction); } } else if (version == installedVersion) { r = PLUGIN_ALREADY_INSTALLED; } else { r = PLUGIN_OLD_VERSION; } } } else { archiver::uncompressArchive(jplPath, destinationDir, PluginUtils::uncompressJplFunction); } if (!libjami::getPluginsEnabled()) { libjami::setPluginsEnabled(true); Manager::instance().saveConfig(); loadPlugins(); return r; } libjami::loadPlugin(destinationDir); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } } return r; } int JamiPluginManager::uninstallPlugin(const std::string& rootPath) { std::error_code ec; if (PluginUtils::checkPluginValidity(rootPath)) { auto detailsIt = pluginDetailsMap_.find(rootPath); if (detailsIt != pluginDetailsMap_.end()) { bool loaded = pm_.checkLoadedPlugin(rootPath); if (loaded) { JAMI_INFO() << "PLUGIN: unloading before uninstall."; bool status = libjami::unloadPlugin(rootPath); if (!status) { JAMI_INFO() << "PLUGIN: unable to unload, not performing uninstall."; return FAILURE; } } for (const auto& accId : jami::Manager::instance().getAccountList()) std::filesystem::remove_all(fileutils::get_data_dir() / accId / "plugins" / detailsIt->second.at("id"), ec); pluginDetailsMap_.erase(detailsIt); } return std::filesystem::remove_all(rootPath, ec) ? SUCCESS : FAILURE; } else { JAMI_INFO() << "PLUGIN: not installed."; return FAILURE; } } bool JamiPluginManager::loadPlugin(const std::string& rootPath) { #ifdef ENABLE_PLUGIN try { bool status = pm_.load(getPluginDetails(rootPath).at("soPath")); JAMI_INFO() << "PLUGIN: load status - " << status; return status; } catch (const std::exception& e) { JAMI_ERR() << e.what(); return false; } #endif return false; } bool JamiPluginManager::loadPlugins() { #ifdef ENABLE_PLUGIN bool status = true; auto loadedPlugins = jami::Manager::instance().pluginPreferences.getLoadedPlugins(); for (const auto& pluginPath : loadedPlugins) { status &= loadPlugin(pluginPath); } return status; #endif return false; } bool JamiPluginManager::unloadPlugin(const std::string& rootPath) { #ifdef ENABLE_PLUGIN try { bool status = pm_.unload(getPluginDetails(rootPath).at("soPath")); JAMI_INFO() << "PLUGIN: unload status - " << status; return status; } catch (const std::exception& e) { JAMI_ERR() << e.what(); return false; } #endif return false; } std::vector<std::string> JamiPluginManager::getLoadedPlugins() const { std::vector<std::string> loadedSoPlugins = pm_.getLoadedPlugins(); std::vector<std::string> loadedPlugins {}; loadedPlugins.reserve(loadedSoPlugins.size()); std::transform(loadedSoPlugins.begin(), loadedSoPlugins.end(), std::back_inserter(loadedPlugins), [](const std::string& soPath) { return PluginUtils::getRootPathFromSoPath(soPath).string(); }); return loadedPlugins; } std::vector<std::map<std::string, std::string>> JamiPluginManager::getPluginPreferences(const std::string& rootPath, const std::string& accountId) { return PluginPreferencesUtils::getPreferences(rootPath, accountId); } bool JamiPluginManager::setPluginPreference(const std::filesystem::path& rootPath, const std::string& accountId, const std::string& key, const std::string& value) { std::string acc = accountId; // If we try to change a preference value linked to an account // but that preference is global, we must ignore accountId and // change the preference for every account if (!accountId.empty()) { // Get global preferences auto preferences = PluginPreferencesUtils::getPreferences(rootPath, ""); // Check if the preference we want to change is global auto it = std::find_if(preferences.cbegin(), preferences.cend(), [key](const std::map<std::string, std::string>& preference) { return preference.at("key") == key; }); // Ignore accountId if global preference if (it != preferences.cend()) acc.clear(); } std::map<std::string, std::string> pluginUserPreferencesMap = PluginPreferencesUtils::getUserPreferencesValuesMap(rootPath, acc); std::map<std::string, std::string> pluginPreferencesMap = PluginPreferencesUtils::getPreferencesValuesMap(rootPath, acc); // If any plugin handler is active we may have to reload it bool force {pm_.checkLoadedPlugin(rootPath.string())}; // We check if the preference is modified without having to reload plugin force &= preferencesm_.setPreference(key, value, rootPath.string(), acc); force &= callsm_.setPreference(key, value, rootPath.string()); force &= chatsm_.setPreference(key, value, rootPath.string()); if (force) unloadPlugin(rootPath.string()); // Save preferences.msgpack with modified preferences values auto find = pluginPreferencesMap.find(key); if (find != pluginPreferencesMap.end()) { pluginUserPreferencesMap[key] = value; auto preferencesValuesFilePath = PluginPreferencesUtils::valuesFilePath(rootPath, acc); std::lock_guard guard(dhtnet::fileutils::getFileLock(preferencesValuesFilePath)); std::ofstream fs(preferencesValuesFilePath, std::ios::binary); if (!fs.good()) { if (force) { loadPlugin(rootPath.string()); } return false; } try { msgpack::pack(fs, pluginUserPreferencesMap); } catch (const std::exception& e) { JAMI_ERR() << e.what(); if (force) { loadPlugin(rootPath.string()); } return false; } } if (force) { loadPlugin(rootPath.string()); } return true; } std::map<std::string, std::string> JamiPluginManager::getPluginPreferencesValuesMap(const std::string& rootPath, const std::string& accountId) { return PluginPreferencesUtils::getPreferencesValuesMap(rootPath, accountId); } bool JamiPluginManager::resetPluginPreferencesValuesMap(const std::string& rootPath, const std::string& accountId) { bool acc {accountId.empty()}; bool loaded {pm_.checkLoadedPlugin(rootPath)}; if (loaded && acc) unloadPlugin(rootPath); auto status = PluginPreferencesUtils::resetPreferencesValuesMap(rootPath, accountId); preferencesm_.resetPreferences(rootPath, accountId); if (loaded && acc) { loadPlugin(rootPath); } return status; } void JamiPluginManager::registerServices() { // Register getPluginPreferences so that plugin's can receive it's preferences pm_.registerService("getPluginPreferences", [](const DLPlugin* plugin, void* data) { auto ppp = static_cast<std::map<std::string, std::string>*>(data); *ppp = PluginPreferencesUtils::getPreferencesValuesMap( PluginUtils::getRootPathFromSoPath(plugin->getPath())); return SUCCESS; }); // Register getPluginDataPath so that plugin's can receive the path to it's data folder pm_.registerService("getPluginDataPath", [](const DLPlugin* plugin, void* data) { auto dataPath = static_cast<std::string*>(data); dataPath->assign(PluginUtils::dataPath(plugin->getPath()).string()); return SUCCESS; }); // getPluginAccPreferences is a service that allows plugins to load saved per account preferences. auto getPluginAccPreferences = [](const DLPlugin* plugin, void* data) { const auto path = PluginUtils::getRootPathFromSoPath(plugin->getPath()); auto preferencesPtr {(static_cast<PreferencesMap*>(data))}; if (!preferencesPtr) return FAILURE; preferencesPtr->emplace("default", PluginPreferencesUtils::getPreferencesValuesMap(path, "default")); for (const auto& accId : jami::Manager::instance().getAccountList()) preferencesPtr->emplace(accId, PluginPreferencesUtils::getPreferencesValuesMap(path, accId)); return SUCCESS; }; pm_.registerService("getPluginAccPreferences", getPluginAccPreferences); } void JamiPluginManager::addPluginAuthority(const dht::crypto::Certificate& cert) { trust_.add(cert); } } // namespace jami
19,606
C++
.cpp
496
30.959677
134
0.625269
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,824
pluginloader.cpp
savoirfairelinux_jami-daemon/src/plugin/pluginloader.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "pluginloader.h" namespace jami { Plugin* Plugin::load(const std::string& path, std::string& error) { if (path.empty()) { error = "Empty path"; return nullptr; } // Clear any existing error ::dlerror(); void* handle = ::dlopen(path.c_str(), RTLD_NOW); if (!handle) { error += "Failed to load \"" + path + '"'; std::string dlError = ::dlerror(); if (dlError.size()) error += " (" + dlError + ")"; return nullptr; } return new DLPlugin(handle, path); } } // namespace jami
1,296
C++
.cpp
38
30.105263
73
0.665068
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,825
pluginpreferencesutils.cpp
savoirfairelinux_jami-daemon/src/plugin/pluginpreferencesutils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "pluginpreferencesutils.h" #include "pluginsutils.h" #include <msgpack.hpp> #include <sstream> #include <fstream> #include <fmt/core.h> #include "logger.h" #include "fileutils.h" namespace jami { std::filesystem::path PluginPreferencesUtils::getPreferencesConfigFilePath(const std::filesystem::path& rootPath, const std::string& accountId) { if (accountId.empty()) return rootPath / "data" / "preferences.json"; else return rootPath / "data" / "accountpreferences.json"; } std::filesystem::path PluginPreferencesUtils::valuesFilePath(const std::filesystem::path& rootPath, const std::string& accountId) { if (accountId.empty() || accountId == "default") return rootPath / "preferences.msgpack"; auto pluginName = rootPath.filename(); auto dir = fileutils::get_data_dir() / accountId / "plugins" / pluginName; dhtnet::fileutils::check_dir(dir); return dir / "preferences.msgpack"; } std::filesystem::path PluginPreferencesUtils::getAllowDenyListsPath() { return fileutils::get_data_dir() / "plugins" / "allowdeny.msgpack"; } std::string PluginPreferencesUtils::convertArrayToString(const Json::Value& jsonArray) { std::string stringArray {}; if (jsonArray.size()) { for (unsigned i = 0; i < jsonArray.size() - 1; i++) { if (jsonArray[i].isString()) { stringArray += jsonArray[i].asString() + ","; } else if (jsonArray[i].isArray()) { stringArray += convertArrayToString(jsonArray[i]) + ","; } } unsigned lastIndex = jsonArray.size() - 1; if (jsonArray[lastIndex].isString()) { stringArray += jsonArray[lastIndex].asString(); } } return stringArray; } std::map<std::string, std::string> PluginPreferencesUtils::parsePreferenceConfig(const Json::Value& jsonPreference) { std::map<std::string, std::string> preferenceMap; const auto& members = jsonPreference.getMemberNames(); // Insert other fields for (const auto& member : members) { const Json::Value& value = jsonPreference[member]; if (value.isString()) { preferenceMap.emplace(member, jsonPreference[member].asString()); } else if (value.isArray()) { preferenceMap.emplace(member, convertArrayToString(jsonPreference[member])); } } return preferenceMap; } std::vector<std::map<std::string, std::string>> PluginPreferencesUtils::getPreferences(const std::filesystem::path& rootPath, const std::string& accountId) { auto preferenceFilePath = getPreferencesConfigFilePath(rootPath, accountId); std::lock_guard guard(dhtnet::fileutils::getFileLock(preferenceFilePath)); std::ifstream file(preferenceFilePath); Json::Value root; Json::CharReaderBuilder rbuilder; rbuilder["collectComments"] = false; std::string errs; std::set<std::string> keys; std::vector<std::map<std::string, std::string>> preferences; if (file) { // Get preferences locale const auto& lang = PluginUtils::getLanguage(); auto locales = PluginUtils::getLocales(rootPath.string(), std::string(string_remove_suffix(lang, '.'))); // Read the file to a json format bool ok = Json::parseFromStream(rbuilder, file, &root, &errs); if (ok && root.isArray()) { // Read each preference described in preference.json individually for (unsigned i = 0; i < root.size(); i++) { const Json::Value& jsonPreference = root[i]; std::string category = jsonPreference.get("category", "NoCategory").asString(); std::string type = jsonPreference.get("type", "None").asString(); std::string key = jsonPreference.get("key", "None").asString(); // The preference must have at least type and key if (type != "None" && key != "None") { if (keys.find(key) == keys.end()) { // Read the rest of the preference auto preferenceAttributes = parsePreferenceConfig(jsonPreference); // If the parsing of the attributes was successful, commit the map and the keys auto defaultValue = preferenceAttributes.find("defaultValue"); if (type == "Path" && defaultValue != preferenceAttributes.end()) { // defaultValue in a Path preference is an incomplete path // starting from the installation path of the plugin. // Here we complete the path value. defaultValue->second = (rootPath / defaultValue->second).string(); } if (!preferenceAttributes.empty()) { for (const auto& locale : locales) { for (auto& pair : preferenceAttributes) { string_replace(pair.second, "{{" + locale.first + "}}", locale.second); } } preferences.push_back(std::move(preferenceAttributes)); keys.insert(key); } } } } } else { JAMI_ERR() << "PluginPreferencesParser:: Failed to parse preferences.json for plugin: " << preferenceFilePath; } } return preferences; } std::map<std::string, std::string> PluginPreferencesUtils::getUserPreferencesValuesMap(const std::filesystem::path& rootPath, const std::string& accountId) { auto preferencesValuesFilePath = valuesFilePath(rootPath, accountId); std::lock_guard guard(dhtnet::fileutils::getFileLock(preferencesValuesFilePath)); std::ifstream file(preferencesValuesFilePath, std::ios::binary); std::map<std::string, std::string> rmap; // If file is accessible if (file.good()) { // Get file size std::string str; file.seekg(0, std::ios::end); size_t fileSize = static_cast<size_t>(file.tellg()); // If not empty if (fileSize > 0) { // Read whole file content and put it in the string str str.reserve(static_cast<size_t>(file.tellg())); file.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); file.close(); try { // Unpack the string msgpack::object_handle oh = msgpack::unpack(str.data(), str.size()); // Deserialized object is valid during the msgpack::object_handle instance is alive. msgpack::object deserialized = oh.get(); deserialized.convert(rmap); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } } } return rmap; } std::map<std::string, std::string> PluginPreferencesUtils::getPreferencesValuesMap(const std::filesystem::path& rootPath, const std::string& accountId) { std::map<std::string, std::string> rmap; // Read all preferences values std::vector<std::map<std::string, std::string>> preferences = getPreferences(rootPath); auto accPrefs = getPreferences(rootPath, accountId); for (const auto& item : accPrefs) { preferences.push_back(item); } for (auto& preference : preferences) { rmap[preference["key"]] = preference["defaultValue"]; } // If any of these preferences were modified, its value is changed before return for (const auto& pair : getUserPreferencesValuesMap(rootPath)) { rmap[pair.first] = pair.second; } if (!accountId.empty()) { // If any of these preferences were modified, its value is changed before return for (const auto& pair : getUserPreferencesValuesMap(rootPath, accountId)) { rmap[pair.first] = pair.second; } } return rmap; } bool PluginPreferencesUtils::resetPreferencesValuesMap(const std::string& rootPath, const std::string& accountId) { bool returnValue = true; std::map<std::string, std::string> pluginPreferencesMap {}; auto preferencesValuesFilePath = valuesFilePath(rootPath, accountId); std::lock_guard guard(dhtnet::fileutils::getFileLock(preferencesValuesFilePath)); std::ofstream fs(preferencesValuesFilePath, std::ios::binary); if (!fs.good()) { return false; } try { msgpack::pack(fs, pluginPreferencesMap); } catch (const std::exception& e) { returnValue = false; JAMI_ERR() << e.what(); } return returnValue; } void PluginPreferencesUtils::setAllowDenyListPreferences(const ChatHandlerList& list) { auto filePath = getAllowDenyListsPath(); std::lock_guard guard(dhtnet::fileutils::getFileLock(filePath)); std::ofstream fs(filePath, std::ios::binary); if (!fs.good()) { return; } try { msgpack::pack(fs, list); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } } void PluginPreferencesUtils::getAllowDenyListPreferences(ChatHandlerList& list) { auto filePath = getAllowDenyListsPath(); std::lock_guard guard(dhtnet::fileutils::getFileLock(filePath)); std::ifstream file(filePath, std::ios::binary); // If file is accessible if (file.good()) { // Get file size std::string str; file.seekg(0, std::ios::end); size_t fileSize = static_cast<size_t>(file.tellg()); // If not empty if (fileSize > 0) { // Read whole file content and put it in the string str str.reserve(static_cast<size_t>(file.tellg())); file.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); file.close(); try { // Unpack the string msgpack::object_handle oh = msgpack::unpack(str.data(), str.size()); // Deserialized object is valid during the msgpack::object_handle instance is alive. msgpack::object deserialized = oh.get(); deserialized.convert(list); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } } } } void PluginPreferencesUtils::addAlwaysHandlerPreference(const std::string& handlerName, const std::string& rootPath) { { auto filePath = getPreferencesConfigFilePath(rootPath); Json::Value root; std::lock_guard guard(dhtnet::fileutils::getFileLock(filePath)); std::ifstream file(filePath); Json::CharReaderBuilder rbuilder; Json::Value preference; rbuilder["collectComments"] = false; std::string errs; if (file) { bool ok = Json::parseFromStream(rbuilder, file, &root, &errs); if (ok && root.isArray()) { // Return if preference already exists for (const auto& child : root) if (child.get("key", "None").asString() == handlerName + "Always") return; } } } auto filePath = getPreferencesConfigFilePath(rootPath, "acc"); Json::Value root; { std::lock_guard guard(dhtnet::fileutils::getFileLock(filePath)); std::ifstream file(filePath); Json::CharReaderBuilder rbuilder; Json::Value preference; rbuilder["collectComments"] = false; std::string errs; if (file) { bool ok = Json::parseFromStream(rbuilder, file, &root, &errs); if (ok && root.isArray()) { // Return if preference already exists for (const auto& child : root) if (child.get("key", "None").asString() == handlerName + "Always") return; } } // Create preference structure otherwise preference["key"] = handlerName + "Always"; preference["type"] = "Switch"; preference["defaultValue"] = "0"; preference["title"] = "Automatically turn " + handlerName + " on"; preference["summary"] = handlerName + " will take effect immediately"; preference["scope"] = "accountId"; root.append(preference); } std::lock_guard guard(dhtnet::fileutils::getFileLock(filePath)); std::ofstream outFile(filePath); if (outFile) { // Save preference.json file with new "always preference" outFile << root.toStyledString(); outFile.close(); } } bool PluginPreferencesUtils::getAlwaysPreference(const std::string& rootPath, const std::string& handlerName, const std::string& accountId) { auto preferences = getPreferences(rootPath); auto accPrefs = getPreferences(rootPath, accountId); for (const auto& item : accPrefs) { preferences.push_back(item); } auto preferencesValues = getPreferencesValuesMap(rootPath, accountId); for (const auto& preference : preferences) { auto key = preference.at("key"); if (preference.at("type") == "Switch" && key == handlerName + "Always" && preferencesValues.find(key)->second == "1") return true; } return false; } } // namespace jami
14,588
C++
.cpp
347
32.414986
112
0.60207
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,826
pluginmanager.cpp
savoirfairelinux_jami-daemon/src/plugin/pluginmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "pluginmanager.h" #include "logger.h" #include <utility> namespace jami { PluginManager::PluginManager() { pluginApi_.context = reinterpret_cast<void*>(this); } PluginManager::~PluginManager() { for (auto& func : exitFunc_) { try { func.second(); } catch (...) { JAMI_ERR() << "Exception caught during plugin exit"; } } dynPluginMap_.clear(); exactMatchMap_.clear(); wildCardVec_.clear(); exitFunc_.clear(); } bool PluginManager::load(const std::string& path) { auto it = dynPluginMap_.find(path); if (it != dynPluginMap_.end()) { unload(path); } std::string error; // Load plugin library std::unique_ptr<Plugin> plugin(Plugin::load(path, error)); if (!plugin) { JAMI_ERR() << "Plugin: " << error; return false; } // Get init function from loaded library const auto& init_func = plugin->getInitFunction(); if (!init_func) { JAMI_ERR() << "Plugin: no init symbol" << error; return false; } // Register plugin by running init function if (!registerPlugin(plugin)) return false; // Put Plugin loader into loaded plugins Map. dynPluginMap_[path] = {std::move(plugin), true}; return true; } bool PluginManager::unload(const std::string& path) { destroyPluginComponents(path); auto it = dynPluginMap_.find(path); if (it != dynPluginMap_.end()) { std::lock_guard lk(mtx_); exitFunc_[path](); dynPluginMap_.erase(it); exitFunc_.erase(path); } return true; } bool PluginManager::checkLoadedPlugin(const std::string& rootPath) const { for (const auto& item : dynPluginMap_) { if (item.first.find(rootPath) != std::string::npos && item.second.second) return true; } return false; } std::vector<std::string> PluginManager::getLoadedPlugins() const { std::vector<std::string> res {}; for (const auto& pair : dynPluginMap_) { if (pair.second.second) res.push_back(pair.first); } return res; } void PluginManager::destroyPluginComponents(const std::string& path) { auto itComponents = pluginComponentsMap_.find(path); if (itComponents != pluginComponentsMap_.end()) { for (auto pairIt = itComponents->second.begin(); pairIt != itComponents->second.end();) { auto clcm = componentsLifeCycleManagers_.find(pairIt->first); if (clcm != componentsLifeCycleManagers_.end()) { clcm->second.destroyComponent(pairIt->second, mtx_); pairIt = itComponents->second.erase(pairIt); } } } } bool PluginManager::callPluginInitFunction(const std::string& path) { bool returnValue {false}; auto it = dynPluginMap_.find(path); if (it != dynPluginMap_.end()) { // Since the Plugin was found it's of type DLPlugin with a valid init symbol std::shared_ptr<DLPlugin> plugin = std::static_pointer_cast<DLPlugin>(it->second.first); const auto& initFunc = plugin->getInitFunction(); JAMI_PluginExitFunc exitFunc = nullptr; try { // Call Plugin Init function exitFunc = initFunc(&plugin->api_); } catch (const std::runtime_error& e) { JAMI_ERR() << e.what(); return false; } if (!exitFunc) { JAMI_ERR() << "Plugin: init failed"; // emit signal with error message to let user know that jamid was unable to load plugin returnValue = false; } else { returnValue = true; } } return returnValue; } bool PluginManager::registerPlugin(std::unique_ptr<Plugin>& plugin) { // Here we already know that Plugin is of type DLPlugin with a valid init symbol const auto& initFunc = plugin->getInitFunction(); DLPlugin* pluginPtr = static_cast<DLPlugin*>(plugin.get()); JAMI_PluginExitFunc exitFunc = nullptr; pluginPtr->apiContext_ = this; pluginPtr->api_.version = {JAMI_PLUGIN_ABI_VERSION, JAMI_PLUGIN_API_VERSION}; pluginPtr->api_.registerObjectFactory = registerObjectFactory_; // Implements JAMI_PluginAPI.invokeService(). // Must be C accessible. pluginPtr->api_.invokeService = [](const JAMI_PluginAPI* api, const char* name, void* data) { auto plugin = static_cast<DLPlugin*>(api->context); auto manager = reinterpret_cast<PluginManager*>(plugin->apiContext_); if (!manager) { JAMI_ERR() << "invokeService called with null plugin API"; return -1; } return manager->invokeService(plugin, name, data); }; // Implements JAMI_PluginAPI.manageComponents(). // Must be C accessible. pluginPtr->api_.manageComponent = [](const JAMI_PluginAPI* api, const char* name, void* data) { auto plugin = static_cast<DLPlugin*>(api->context); if (!plugin) { JAMI_ERR() << "createComponent called with null context"; return -1; } auto manager = reinterpret_cast<PluginManager*>(plugin->apiContext_); if (!manager) { JAMI_ERR() << "createComponent called with null plugin API"; return -1; } return manager->manageComponent(plugin, name, data); }; try { exitFunc = initFunc(&pluginPtr->api_); } catch (const std::runtime_error& e) { JAMI_ERR() << e.what(); } if (!exitFunc) { JAMI_ERR() << "Plugin: init failed"; return false; } exitFunc_[pluginPtr->getPath()] = exitFunc; return true; } bool PluginManager::registerService(const std::string& name, ServiceFunction&& func) { services_[name] = std::forward<ServiceFunction>(func); return true; } void PluginManager::unRegisterService(const std::string& name) { services_.erase(name); } int32_t PluginManager::invokeService(const DLPlugin* plugin, const std::string& name, void* data) { // Search if desired service exists const auto& iterFunc = services_.find(name); if (iterFunc == services_.cend()) { JAMI_ERR() << "Services not found: " << name; return -1; } const auto& func = iterFunc->second; try { // Call service with data return func(plugin, data); } catch (const std::runtime_error& e) { JAMI_ERR() << e.what(); return -1; } } int32_t PluginManager::manageComponent(const DLPlugin* plugin, const std::string& name, void* data) { const auto& iter = componentsLifeCycleManagers_.find(name); if (iter == componentsLifeCycleManagers_.end()) { JAMI_ERR() << "Component lifecycle manager not found: " << name; return -1; } const auto& componentLifecycleManager = iter->second; try { int32_t r = componentLifecycleManager.takeComponentOwnership(data, mtx_); if (r == 0) { pluginComponentsMap_[plugin->getPath()].emplace_back(name, data); } return r; } catch (const std::runtime_error& e) { JAMI_ERR() << e.what(); return -1; } } bool PluginManager::registerObjectFactory(const char* type, const JAMI_PluginObjectFactory& factoryData) { if (!type) return false; if (!factoryData.create || !factoryData.destroy) return false; // Strict compatibility on ABI if (factoryData.version.abi != pluginApi_.version.abi) return false; // Backward compatibility on API if (factoryData.version.api < pluginApi_.version.api) return false; const std::string key(type); auto deleter = [factoryData](void* o) { factoryData.destroy(o, factoryData.closure); }; ObjectFactory factory = {factoryData, deleter}; // Wildcard registration if (key == "*") { wildCardVec_.push_back(factory); return true; } // Fails on duplicate for exactMatch map if (exactMatchMap_.find(key) != exactMatchMap_.end()) return false; exactMatchMap_[key] = factory; return true; } bool PluginManager::registerComponentManager(const std::string& name, ComponentFunction&& takeOwnership, ComponentFunction&& destroyComponent) { componentsLifeCycleManagers_[name] = {std::forward<ComponentFunction>(takeOwnership), std::forward<ComponentFunction>(destroyComponent)}; return true; } std::unique_ptr<void, PluginManager::ObjectDeleter> PluginManager::createObject(const std::string& type) { if (type == "*") return {nullptr, nullptr}; JAMI_PluginObjectParams op = { /*.pluginApi = */ &pluginApi_, /*.type = */ type.c_str(), }; // Try to find an exact match const auto& factoryIter = exactMatchMap_.find(type); if (factoryIter != exactMatchMap_.end()) { const auto& factory = factoryIter->second; auto object = factory.data.create(&op, factory.data.closure); if (object) return {object, factory.deleter}; } // Try to find a wildcard match for (const auto& factory : wildCardVec_) { auto object = factory.data.create(&op, factory.data.closure); if (object) { // Promote registration to exactMatch_ // (but keep also wildcard registration for other object types) int32_t res = registerObjectFactory(op.type, factory.data); if (res < 0) { JAMI_ERR() << "failed to register object " << op.type; return {nullptr, nullptr}; } return {object, factory.deleter}; } } return {nullptr, nullptr}; } int32_t PluginManager::registerObjectFactory_(const JAMI_PluginAPI* api, const char* type, void* data) { auto manager = reinterpret_cast<PluginManager*>(api->context); if (!manager) { JAMI_ERR() << "registerObjectFactory called with null plugin API"; return -1; } if (!data) { JAMI_ERR() << "registerObjectFactory called with null factory data"; return -1; } const auto factory = reinterpret_cast<JAMI_PluginObjectFactory*>(data); return manager->registerObjectFactory(type, *factory) ? 0 : -1; } } // namespace jami
11,057
C++
.cpp
322
28.024845
99
0.637674
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,827
callservicesmanager.cpp
savoirfairelinux_jami-daemon/src/plugin/callservicesmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "callservicesmanager.h" #include "pluginmanager.h" #include "pluginpreferencesutils.h" #include "manager.h" #include "sip/sipcall.h" #include "fileutils.h" #include "logger.h" namespace jami { CallServicesManager::CallServicesManager(PluginManager& pluginManager) { registerComponentsLifeCycleManagers(pluginManager); } CallServicesManager::~CallServicesManager() { callMediaHandlers_.clear(); callAVsubjects_.clear(); mediaHandlerToggled_.clear(); } void CallServicesManager::createAVSubject(const StreamData& data, AVSubjectSPtr subject) { auto predicate = [&data](std::pair<const StreamData, AVSubjectSPtr> item) { return data.id == item.first.id && data.direction == item.first.direction && data.type == item.first.type; }; callAVsubjects_[data.id].remove_if(predicate); // callAVsubjects_ emplaces data and subject with callId key to easy of access // When call is ended, subjects from this call are erased. callAVsubjects_[data.id].emplace_back(data, subject); // Search for activation flag. for (auto& callMediaHandler : callMediaHandlers_) { std::size_t found = callMediaHandler->id().find_last_of(DIR_SEPARATOR_CH); // toggle is true if we should automatically activate the MediaHandler. bool toggle = PluginPreferencesUtils::getAlwaysPreference( callMediaHandler->id().substr(0, found), callMediaHandler->getCallMediaHandlerDetails().at("name"), data.source); // toggle may be overwritten if the MediaHandler was previously activated/deactivated // for the given call. for (const auto& toggledMediaHandlerPair : mediaHandlerToggled_[data.id]) { if (toggledMediaHandlerPair.first == (uintptr_t) callMediaHandler.get()) { toggle = toggledMediaHandlerPair.second; break; } } if (toggle) #ifndef __ANDROID__ // If activation is expected, we call activation function toggleCallMediaHandler((uintptr_t) callMediaHandler.get(), data.id, true); #else // Due to Android's camera activation process, we don't automaticaly // activate the MediaHandler here. But we set it as active // and the client-android will handle its activation. mediaHandlerToggled_[data.id].insert({(uintptr_t) callMediaHandler.get(), true}); #endif } } void CallServicesManager::clearAVSubject(const std::string& callId) { callAVsubjects_.erase(callId); } void CallServicesManager::registerComponentsLifeCycleManagers(PluginManager& pluginManager) { // registerMediaHandler may be called by the PluginManager upon loading a plugin. auto registerMediaHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); CallMediaHandlerPtr ptr {(static_cast<CallMediaHandler*>(data))}; if (!ptr) return -1; std::size_t found = ptr->id().find_last_of(DIR_SEPARATOR_CH); // Adding preference that tells us to automatically activate a MediaHandler. PluginPreferencesUtils::addAlwaysHandlerPreference(ptr->getCallMediaHandlerDetails().at( "name"), ptr->id().substr(0, found)); callMediaHandlers_.emplace_back(std::move(ptr)); return 0; }; // unregisterMediaHandler may be called by the PluginManager while unloading. auto unregisterMediaHandler = [this](void* data, std::mutex& pmMtx_) { std::lock_guard lk(pmMtx_); auto handlerIt = std::find_if(callMediaHandlers_.begin(), callMediaHandlers_.end(), [data](CallMediaHandlerPtr& handler) { return (handler.get() == data); }); if (handlerIt != callMediaHandlers_.end()) { for (auto& toggledList : mediaHandlerToggled_) { auto handlerId = std::find_if(toggledList.second.begin(), toggledList.second.end(), [handlerIt]( std::pair<uintptr_t, bool> handlerIdPair) { return handlerIdPair.first == (uintptr_t) handlerIt->get() && handlerIdPair.second; }); // If MediaHandler is attempting to destroy one which is currently in use, we deactivate it. if (handlerId != toggledList.second.end()) toggleCallMediaHandler((*handlerId).first, toggledList.first, false); } callMediaHandlers_.erase(handlerIt); } return true; }; // Services are registered to the PluginManager. pluginManager.registerComponentManager("CallMediaHandlerManager", registerMediaHandler, unregisterMediaHandler); } std::vector<std::string> CallServicesManager::getCallMediaHandlers() { std::vector<std::string> res; res.reserve(callMediaHandlers_.size()); for (const auto& mediaHandler : callMediaHandlers_) { res.emplace_back(std::to_string((uintptr_t) mediaHandler.get())); } return res; } void CallServicesManager::toggleCallMediaHandler(const std::string& mediaHandlerId, const std::string& callId, const bool toggle) { try { toggleCallMediaHandler(std::stoull(mediaHandlerId), callId, toggle); } catch (const std::exception& e) { JAMI_ERR("Error toggling media handler: %s", e.what()); } } std::map<std::string, std::string> CallServicesManager::getCallMediaHandlerDetails(const std::string& mediaHandlerIdStr) { auto mediaHandlerId = std::stoull(mediaHandlerIdStr); for (auto& mediaHandler : callMediaHandlers_) { if ((uintptr_t) mediaHandler.get() == mediaHandlerId) { return mediaHandler->getCallMediaHandlerDetails(); } } return {}; } bool CallServicesManager::isVideoType(const CallMediaHandlerPtr& mediaHandler) { // "dataType" is known from the MediaHandler implementation. const auto& details = mediaHandler->getCallMediaHandlerDetails(); const auto& it = details.find("dataType"); if (it != details.end()) { bool status; std::istringstream(it->second) >> status; return status; } // If there is no "dataType" returned, it's safer to return True and allow // sender to restart. return true; } bool CallServicesManager::isAttached(const CallMediaHandlerPtr& mediaHandler) { // "attached" is known from the MediaHandler implementation. const auto& details = mediaHandler->getCallMediaHandlerDetails(); const auto& it = details.find("attached"); if (it != details.end()) { bool status; std::istringstream(it->second) >> status; return status; } return true; } std::vector<std::string> CallServicesManager::getCallMediaHandlerStatus(const std::string& callId) { std::vector<std::string> ret; const auto& it = mediaHandlerToggled_.find(callId); if (it != mediaHandlerToggled_.end()) for (const auto& mediaHandlerId : it->second) if (mediaHandlerId.second) // Only return active MediaHandler ids ret.emplace_back(std::to_string(mediaHandlerId.first)); return ret; } bool CallServicesManager::setPreference(const std::string& key, const std::string& value, const std::string& rootPath) { bool status {true}; for (auto& mediaHandler : callMediaHandlers_) { if (mediaHandler->id().find(rootPath) != std::string::npos) { if (mediaHandler->preferenceMapHasKey(key)) { mediaHandler->setPreferenceAttribute(key, value); status &= false; } } } return status; } void CallServicesManager::clearCallHandlerMaps(const std::string& callId) { mediaHandlerToggled_.erase(callId); } void CallServicesManager::notifyAVSubject(CallMediaHandlerPtr& callMediaHandlerPtr, const StreamData& data, AVSubjectSPtr& subject) { if (auto soSubject = subject.lock()) callMediaHandlerPtr->notifyAVFrameSubject(data, soSubject); } void CallServicesManager::toggleCallMediaHandler(const uintptr_t mediaHandlerId, const std::string& callId, const bool toggle) { auto& handlers = mediaHandlerToggled_[callId]; bool applyRestart = false; for (auto subject : callAVsubjects_[callId]) { auto handlerIt = std::find_if(callMediaHandlers_.begin(), callMediaHandlers_.end(), [mediaHandlerId](CallMediaHandlerPtr& handler) { return ((uintptr_t) handler.get() == mediaHandlerId); }); if (handlerIt != callMediaHandlers_.end()) { if (toggle) { notifyAVSubject((*handlerIt), subject.first, subject.second); if (isAttached((*handlerIt))) handlers[mediaHandlerId] = true; } else { (*handlerIt)->detach(); handlers[mediaHandlerId] = false; } if (subject.first.type == StreamType::video && isVideoType((*handlerIt))) applyRestart = true; } } #ifndef __ANDROID__ #ifdef ENABLE_VIDEO if (applyRestart) { auto call = Manager::instance().callFactory.getCall<SIPCall>(callId); if (call && !call->isConferenceParticipant()) { for (auto const& videoRtp: call->getRtpSessionList(MediaType::MEDIA_VIDEO)) videoRtp->restartSender(); } } #endif #endif } } // namespace jami
11,130
C++
.cpp
265
31.913208
108
0.615044
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,828
pluginsutils.cpp
savoirfairelinux_jami-daemon/src/plugin/pluginsutils.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "pluginsutils.h" #include "logger.h" #include "fileutils.h" #include "archiver.h" #include <msgpack.hpp> #include <fstream> #include <regex> #if defined(__APPLE__) #if (defined(TARGET_OS_IOS) && TARGET_OS_IOS) #define ABI "iphone" #else #if defined(__x86_64__) #define ABI "x86_64-apple-Darwin" #else #define ABI "arm64-apple-Darwin" #endif #endif #elif defined(__arm__) #if defined(__ARM_ARCH_7A__) #define ABI "armeabi-v7a" #else #define ABI "armeabi" #endif #elif defined(__i386__) #if __ANDROID__ #define ABI "x86" #else #define ABI "x86-linux-gnu" #endif #elif defined(__x86_64__) #if __ANDROID__ #define ABI "x86_64" #else #define ABI "x86_64-linux-gnu" #endif #elif defined(__aarch64__) #define ABI "arm64-v8a" #elif defined(WIN32) #define ABI "x64-windows" #else #define ABI "unknown" #endif namespace jami { namespace PluginUtils { // DATA_REGEX is used to during the plugin jpl uncompressing const std::regex DATA_REGEX("^data" DIR_SEPARATOR_STR_ESC ".+"); // SO_REGEX is used to find libraries during the plugin jpl uncompressing // lib/ABI/libplugin.SO const std::regex SO_REGEX(DIR_SEPARATOR_STR_ESC "(.*)" DIR_SEPARATOR_STR_ESC "([a-zA-Z0-9]+.(dylib|so|dll|lib).*)"); std::filesystem::path manifestPath(const std::filesystem::path& rootPath) { return rootPath / "manifest.json"; } std::map<std::string, std::string> getPlatformInfo() { return { {"os", ABI} }; } std::filesystem::path getRootPathFromSoPath(const std::filesystem::path& soPath) { return soPath.parent_path(); } std::filesystem::path dataPath(const std::filesystem::path& pluginSoPath) { return getRootPathFromSoPath(pluginSoPath) / "data"; } std::map<std::string, std::string> checkManifestJsonContentValidity(const Json::Value& root) { std::string name = root.get("name", "").asString(); std::string id = root.get("id", name).asString(); std::string description = root.get("description", "").asString(); std::string version = root.get("version", "").asString(); std::string iconPath = root.get("iconPath", "icon.png").asString(); std::string background = root.get("backgroundPath", "background.jpg").asString(); if (!name.empty() || !version.empty()) { return { {"id", id}, {"name", name}, {"description", description}, {"version", version}, {"iconPath", iconPath}, {"backgroundPath", background}, }; } else { throw std::runtime_error("plugin manifest file: bad format"); } } std::map<std::string, std::string> checkManifestValidity(std::istream& stream) { Json::Value root; Json::CharReaderBuilder rbuilder; rbuilder["collectComments"] = false; std::string errs; if (Json::parseFromStream(rbuilder, stream, &root, &errs)) { return checkManifestJsonContentValidity(root); } else { throw std::runtime_error("failed to parse the plugin manifest file"); } } std::map<std::string, std::string> checkManifestValidity(const std::vector<uint8_t>& vec) { Json::Value root; std::unique_ptr<Json::CharReader> json_Reader(Json::CharReaderBuilder {}.newCharReader()); std::string errs; bool ok = json_Reader->parse(reinterpret_cast<const char*>(vec.data()), reinterpret_cast<const char*>(vec.data() + vec.size()), &root, &errs); if (ok) { return checkManifestJsonContentValidity(root); } else { throw std::runtime_error("failed to parse the plugin manifest file"); } } std::map<std::string, std::string> parseManifestFile(const std::filesystem::path& manifestFilePath, const std::string& rootPath) { std::lock_guard guard(dhtnet::fileutils::getFileLock(manifestFilePath)); std::ifstream file(manifestFilePath); if (file) { try { const auto& traduction = parseManifestTranslation(rootPath, file); return checkManifestValidity(std::vector<uint8_t>(traduction.begin(), traduction.end())); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } } return {}; } std::string parseManifestTranslation(const std::string& rootPath, std::ifstream& manifestFile) { if (manifestFile) { std::stringstream buffer; buffer << manifestFile.rdbuf(); std::string manifest = buffer.str(); const auto& translation = getLocales(rootPath, getLanguage()); std::regex pattern(R"(\{\{([^}]+)\}\})"); std::smatch matches; // replace the pattern to the correct translation while (std::regex_search(manifest, matches, pattern)) { if (matches.size() == 2) { auto it = translation.find(matches[1].str()); if (it == translation.end()) { manifest = std::regex_replace(manifest, pattern, ""); continue; } manifest = std::regex_replace(manifest, pattern, it->second, std::regex_constants::format_first_only); } } return manifest; } return {}; } bool checkPluginValidity(const std::filesystem::path& rootPath) { return !parseManifestFile(manifestPath(rootPath), rootPath.string()).empty(); } std::map<std::string, std::string> readPluginManifestFromArchive(const std::string& jplPath) { try { return checkManifestValidity(archiver::readFileFromArchive(jplPath, "manifest.json")); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } return {}; } std::unique_ptr<dht::crypto::Certificate> readPluginCertificate(const std::string& rootPath, const std::string& pluginId) { std::string certPath = rootPath + DIR_SEPARATOR_CH + pluginId + ".crt"; try { auto cert = fileutils::loadFile(certPath); return std::make_unique<dht::crypto::Certificate>(cert); } catch (const std::exception& e) { JAMI_ERR() << e.what(); } return {}; } std::unique_ptr<dht::crypto::Certificate> readPluginCertificateFromArchive(const std::string& jplPath) { try { auto manifest = readPluginManifestFromArchive(jplPath); const std::string& name = manifest["id"]; if (name.empty()) { return {}; } return std::make_unique<dht::crypto::Certificate>(archiver::readFileFromArchive(jplPath, name + ".crt")); } catch(const std::exception& e) { JAMI_ERR() << e.what(); return {}; } } std::map<std::string, std::vector<uint8_t>> readPluginSignatureFromArchive(const std::string& jplPath) { try { std::vector<uint8_t> vec = archiver::readFileFromArchive(jplPath, "signatures"); msgpack::object_handle oh = msgpack::unpack( reinterpret_cast<const char*>(vec.data()), vec.size() * sizeof(uint8_t) ); msgpack::object obj = oh.get(); return obj.as<std::map<std::string, std::vector<uint8_t>>>(); } catch(const std::exception& e) { JAMI_ERR() << e.what(); return {}; } } std::vector<uint8_t> readSignatureFileFromArchive(const std::string& jplPath) { return archiver::readFileFromArchive(jplPath, "signatures.sig"); } std::pair<bool, std::string_view> uncompressJplFunction(std::string_view relativeFileName) { std::svmatch match; // manifest.json and files under data/ folder remains in the same structure // but libraries files are extracted from the folder that matches the running ABI to // the main installation path. if (std::regex_search(relativeFileName, match, SO_REGEX)) { if (std::svsub_match_view(match[1]) != ABI) { return std::make_pair(false, std::string_view {}); } else { return std::make_pair(true, std::svsub_match_view(match[2])); } } return std::make_pair(true, relativeFileName); } std::string getLanguage() { std::string lang; if (auto envLang = std::getenv("JAMI_LANG")) lang = envLang; else JAMI_INFO() << "Error getting JAMI_LANG env, attempting to get system language"; // If language preference is empty, try to get from the system. if (lang.empty()) { #ifdef WIN32 WCHAR localeBuffer[LOCALE_NAME_MAX_LENGTH]; if (GetUserDefaultLocaleName(localeBuffer, LOCALE_NAME_MAX_LENGTH) != 0) { char utf8Buffer[LOCALE_NAME_MAX_LENGTH] {}; WideCharToMultiByte(CP_UTF8, 0, localeBuffer, LOCALE_NAME_MAX_LENGTH, utf8Buffer, LOCALE_NAME_MAX_LENGTH, nullptr, nullptr); lang.append(utf8Buffer); string_replace(lang, "-", "_"); } // Even though we default to the system variable in Windows, technically this // part of the code should not be reached because the client-qt must define that // variable and is unable to run the client and the daemon in diferent processes in Windows. #else // The same way described in the comment just above, Android should not reach this // part of the code given the client-android must define "JAMI_LANG" system variable. // And even if this part is reached, it should not work since std::locale is not // supported by the NDK. // LC_COLLATE is used to grab the locale for the case when the system user has set different // values for the preferred Language and Format. lang = setlocale(LC_COLLATE, ""); // We set the environment to avoid checking from system everytime. // This is the case when running daemon and client in different processes // like with dbus. setenv("JAMI_LANG", lang.c_str(), 1); #endif // WIN32 } return lang; } std::map<std::string, std::string> getLocales(const std::string& rootPath, const std::string& lang) { auto pluginName = rootPath.substr(rootPath.find_last_of(DIR_SEPARATOR_CH) + 1); auto basePath = fmt::format("{}/data/locale/{}", rootPath, pluginName + "_"); std::map<std::string, std::string> locales = {}; // Get language translations if (!lang.empty()) { locales = processLocaleFile(basePath + lang + ".json"); } // Get default english values if no translations were found if (locales.empty()) { locales = processLocaleFile(basePath + "en.json"); } return locales; } std::map<std::string, std::string> processLocaleFile(const std::string& preferenceLocaleFilePath) { if (!std::filesystem::is_regular_file(preferenceLocaleFilePath)) { return {}; } std::ifstream file(preferenceLocaleFilePath); Json::Value root; Json::CharReaderBuilder rbuilder; rbuilder["collectComments"] = false; std::string errs; std::map<std::string, std::string> locales {}; if (file) { // Read the file to a json format if (Json::parseFromStream(rbuilder, file, &root, &errs)) { auto keys = root.getMemberNames(); for (const auto& key : keys) { locales[key] = root.get(key, "").asString(); } } } return locales; } } // namespace PluginUtils } // namespace jami
12,452
C++
.cpp
340
29.679412
118
0.625238
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,829
yamlparser.cpp
savoirfairelinux_jami-daemon/src/config/yamlparser.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "yamlparser.h" #include "fileutils.h" namespace jami { namespace yaml_utils { void parsePath(const YAML::Node& node, const char* key, std::string& path, const std::filesystem::path& base) { std::string val; parseValue(node, key, val); path = fileutils::getFullPath(base, val).string(); } void parsePathOptional(const YAML::Node& node, const char* key, std::string& path, const std::filesystem::path& base) { std::string val; if (parseValueOptional(node, key, val)) path = fileutils::getFullPath(base, val).string(); } std::vector<std::map<std::string, std::string>> parseVectorMap(const YAML::Node& node, const std::initializer_list<std::string>& keys) { std::vector<std::map<std::string, std::string>> result; result.reserve(node.size()); for (const auto& n : node) { std::map<std::string, std::string> t; for (const auto& k : keys) { t[k] = n[k].as<std::string>(""); } result.emplace_back(std::move(t)); } return result; } std::set<std::string> parseVector(const YAML::Node& node) { std::set<std::string> result; for (const auto& n : node) { result.emplace(n.as<std::string>("")); } return result; } } // namespace yaml_utils } // namespace jami
1,996
C++
.cpp
59
30.508475
112
0.687727
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,830
sipcall.cpp
savoirfairelinux_jami-daemon/src/sip/sipcall.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "call_factory.h" #include "sip/sipcall.h" #include "sip/sipaccount.h" #include "sip/sipaccountbase.h" #include "sip/sipvoiplink.h" #include "jamidht/jamiaccount.h" #include "logger.h" #include "sdp.h" #include "manager.h" #include "string_utils.h" #include "connectivity/sip_utils.h" #include "audio/audio_rtp_session.h" #include "system_codec_container.h" #include "im/instant_messaging.h" #include "jami/account_const.h" #include "jami/call_const.h" #include "jami/media_const.h" #include "client/ring_signal.h" #include "pjsip-ua/sip_inv.h" #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #endif #ifdef ENABLE_VIDEO #include "client/videomanager.h" #include "video/video_rtp_session.h" #include "jami/videomanager_interface.h" #include <chrono> #include <libavutil/display.h> #include <video/sinkclient.h> #include "media/video/video_mixer.h" #endif #include "audio/ringbufferpool.h" #include "jamidht/channeled_transport.h" #include "errno.h" #include <dhtnet/upnp/upnp_control.h> #include <dhtnet/ice_transport_factory.h> #include <opendht/crypto.h> #include <opendht/thread_pool.h> #include <fmt/ranges.h> #include "tracepoint.h" #include "media/media_decoder.h" namespace jami { using sip_utils::CONST_PJ_STR; using namespace libjami::Call; #ifdef ENABLE_VIDEO static DeviceParams getVideoSettings() { const auto& videomon = jami::getVideoDeviceMonitor(); return videomon.getDeviceParams(videomon.getDefaultDevice()); } #endif static constexpr std::chrono::seconds DEFAULT_ICE_INIT_TIMEOUT {35}; // seconds static constexpr std::chrono::milliseconds EXPECTED_ICE_INIT_MAX_TIME {5000}; static constexpr std::chrono::seconds DEFAULT_ICE_NEGO_TIMEOUT {60}; // seconds static constexpr std::chrono::milliseconds MS_BETWEEN_2_KEYFRAME_REQUEST {1000}; static constexpr int ICE_COMP_ID_RTP {1}; static constexpr int ICE_COMP_COUNT_PER_STREAM {2}; static constexpr auto MULTISTREAM_REQUIRED_VERSION_STR = "10.0.2"sv; static const std::vector<unsigned> MULTISTREAM_REQUIRED_VERSION = split_string_to_unsigned(MULTISTREAM_REQUIRED_VERSION_STR, '.'); static constexpr auto MULTIICE_REQUIRED_VERSION_STR = "13.3.0"sv; static const std::vector<unsigned> MULTIICE_REQUIRED_VERSION = split_string_to_unsigned(MULTIICE_REQUIRED_VERSION_STR, '.'); static constexpr auto NEW_CONFPROTOCOL_VERSION_STR = "13.1.0"sv; static const std::vector<unsigned> NEW_CONFPROTOCOL_VERSION = split_string_to_unsigned(NEW_CONFPROTOCOL_VERSION_STR, '.'); static constexpr auto REUSE_ICE_IN_REINVITE_REQUIRED_VERSION_STR = "11.0.2"sv; static const std::vector<unsigned> REUSE_ICE_IN_REINVITE_REQUIRED_VERSION = split_string_to_unsigned(REUSE_ICE_IN_REINVITE_REQUIRED_VERSION_STR, '.'); static constexpr auto MULTIAUDIO_REQUIRED_VERSION_STR = "13.11.0"sv; static const std::vector<unsigned> MULTIAUDIO_REQUIRED_VERSION = split_string_to_unsigned(MULTIAUDIO_REQUIRED_VERSION_STR, '.'); SIPCall::SIPCall(const std::shared_ptr<SIPAccountBase>& account, const std::string& callId, Call::CallType type, const std::vector<libjami::MediaMap>& mediaList) : Call(account, callId, type) , sdp_(new Sdp(callId)) , enableIce_(account->isIceForMediaEnabled()) , srtpEnabled_(account->isSrtpEnabled()) { jami_tracepoint(call_start, callId.c_str()); if (account->getUPnPActive()) upnp_ = std::make_shared<dhtnet::upnp::Controller>(Manager::instance().upnpContext()); setCallMediaLocal(); // Set the media caps. sdp_->setLocalMediaCapabilities(MediaType::MEDIA_AUDIO, account->getActiveAccountCodecInfoList(MEDIA_AUDIO)); #ifdef ENABLE_VIDEO sdp_->setLocalMediaCapabilities(MediaType::MEDIA_VIDEO, account->getActiveAccountCodecInfoList(MEDIA_VIDEO)); #endif auto mediaAttrList = MediaAttribute::buildMediaAttributesList(mediaList, isSrtpEnabled()); if (mediaAttrList.size() == 0) { if (type_ == Call::CallType::INCOMING) { // Handle incoming call without media offer. JAMI_WARN( "[call:%s] No media offered in the incoming invite. An offer will be provided in " "the answer", getCallId().c_str()); mediaAttrList = getSIPAccount()->createDefaultMediaList(false, getState() == CallState::HOLD); } else { JAMI_WARN("[call:%s] Creating an outgoing call with empty offer", getCallId().c_str()); } } JAMI_DEBUG("[call:{:s}] Create a new [{:s}] SIP call with {:d} media", getCallId(), type == Call::CallType::INCOMING ? "INCOMING" : (type == Call::CallType::OUTGOING ? "OUTGOING" : "MISSED"), mediaList.size()); initMediaStreams(mediaAttrList); } SIPCall::~SIPCall() { std::lock_guard lk {callMutex_}; setSipTransport({}); setInviteSession(); // prevents callback usage #ifdef ENABLE_VIDEO closeMediaPlayer(mediaPlayerId_); #endif } int SIPCall::findRtpStreamIndex(const std::string& label) const { const auto iter = std::find_if(rtpStreams_.begin(), rtpStreams_.end(), [&label](const RtpStream& rtp) { return label == rtp.mediaAttribute_->label_; }); // Return the index if there is a match. if (iter != rtpStreams_.end()) return std::distance(rtpStreams_.begin(), iter); // No match found. return -1; } void SIPCall::createRtpSession(RtpStream& stream) { if (not stream.mediaAttribute_) throw std::runtime_error("Missing media attribute"); // To get audio_0 ; video_0 auto streamId = sip_utils::streamId(id_, stream.mediaAttribute_->label_); if (stream.mediaAttribute_->type_ == MediaType::MEDIA_AUDIO) { stream.rtpSession_ = std::make_shared<AudioRtpSession>(id_, streamId, recorder_); } #ifdef ENABLE_VIDEO else if (stream.mediaAttribute_->type_ == MediaType::MEDIA_VIDEO) { stream.rtpSession_ = std::make_shared<video::VideoRtpSession>(id_, streamId, getVideoSettings(), recorder_); std::static_pointer_cast<video::VideoRtpSession>(stream.rtpSession_)->setRotation(rotation_); } #endif else { throw std::runtime_error("Unsupported media type"); } // Must be valid at this point. if (not stream.rtpSession_) throw std::runtime_error("Failed to create RTP Session"); ; } void SIPCall::configureRtpSession(const std::shared_ptr<RtpSession>& rtpSession, const std::shared_ptr<MediaAttribute>& mediaAttr, const MediaDescription& localMedia, const MediaDescription& remoteMedia) { JAMI_DBG("[call:%s] Configuring [%s] rtp session", getCallId().c_str(), MediaAttribute::mediaTypeToString(mediaAttr->type_)); if (not rtpSession) throw std::runtime_error("Must have a valid RTP Session"); // Configure the media stream auto new_mtu = sipTransport_->getTlsMtu(); rtpSession->setMtu(new_mtu); rtpSession->updateMedia(remoteMedia, localMedia); // Mute/un-mute media if (mediaAttr->muted_) { rtpSession->setMuted(true); // TODO. Setting mute to true should be enough to mute. // Kept for backward compatiblity. rtpSession->setMediaSource(""); } else { rtpSession->setMuted(false); rtpSession->setMediaSource(mediaAttr->sourceUri_); } rtpSession->setSuccessfulSetupCb([w = weak()](MediaType, bool) { // This sends SIP messages on socket, so move to io dht::ThreadPool::io().run([w = std::move(w)] { if (auto thisPtr = w.lock()) thisPtr->rtpSetupSuccess(); }); }); if (localMedia.type == MediaType::MEDIA_AUDIO) { setupVoiceCallback(rtpSession); } #ifdef ENABLE_VIDEO if (localMedia.type == MediaType::MEDIA_VIDEO) { auto videoRtp = std::dynamic_pointer_cast<video::VideoRtpSession>(rtpSession); assert(videoRtp && mediaAttr); auto streamIdx = findRtpStreamIndex(mediaAttr->label_); videoRtp->setRequestKeyFrameCallback([w = weak(), streamIdx] { // This sends SIP messages on socket, so move to io dht::ThreadPool::io().run([w = std::move(w), streamIdx] { if (auto thisPtr = w.lock()) thisPtr->requestKeyframe(streamIdx); }); }); videoRtp->setChangeOrientationCallback([w = weak(), streamIdx](int angle) { // This sends SIP messages on socket, so move to io dht::ThreadPool::io().run([w, angle, streamIdx] { if (auto thisPtr = w.lock()) thisPtr->setVideoOrientation(streamIdx, angle); }); }); } #endif } void SIPCall::setupVoiceCallback(const std::shared_ptr<RtpSession>& rtpSession) { // need to downcast to access setVoiceCallback auto audioRtp = std::dynamic_pointer_cast<AudioRtpSession>(rtpSession); audioRtp->setVoiceCallback([w = weak()](bool voice) { // this is called whenever voice is detected on the local audio runOnMainThread([w, voice] { if (auto thisPtr = w.lock()) { // TODO: once we support multiple streams, change this to the right one std::string streamId = ""; #ifdef ENABLE_VIDEO if (not jami::getVideoDeviceMonitor().getDeviceList().empty()) { // if we have a video device streamId = sip_utils::streamId("", sip_utils::DEFAULT_VIDEO_STREAMID); } #endif // send our local voice activity if (auto conference = thisPtr->conf_.lock()) { // we are in a conference // updates conference info and sends it to others via ConfInfo // (only if there was a change) // also emits signal with updated conference info conference->setVoiceActivity(streamId, voice); } else { // we are in a one-to-one call // send voice activity over SIP // TODO: change the streamID once multiple streams are supported thisPtr->sendVoiceActivity("-1", voice); // TODO: maybe emit signal here for local voice activity } } else { JAMI_ERR("voice activity callback unable to lock weak ptr to SIPCall"); } }); }); } std::shared_ptr<SIPAccountBase> SIPCall::getSIPAccount() const { return std::static_pointer_cast<SIPAccountBase>(getAccount().lock()); } #ifdef ENABLE_PLUGIN void SIPCall::createCallAVStreams() { #ifdef ENABLE_VIDEO for (const auto& videoRtp : getRtpSessionList(MediaType::MEDIA_VIDEO)) { if (std::static_pointer_cast<video::VideoRtpSession>(videoRtp)->hasConference()) { clearCallAVStreams(); return; } } #endif auto baseId = getCallId(); auto mediaMap = [](const std::shared_ptr<jami::MediaFrame>& m) -> AVFrame* { return m->pointer(); }; for (const auto& rtpSession : getRtpSessionList()) { auto isVideo = rtpSession->getMediaType() == MediaType::MEDIA_VIDEO; auto streamType = isVideo ? StreamType::video : StreamType::audio; StreamData previewStreamData {baseId, false, streamType, getPeerNumber(), getAccountId()}; StreamData receiveStreamData {baseId, true, streamType, getPeerNumber(), getAccountId()}; #ifdef ENABLE_VIDEO if (isVideo) { // Preview auto videoRtp = std::static_pointer_cast<video::VideoRtpSession>(rtpSession); if (auto& videoPreview = videoRtp->getVideoLocal()) createCallAVStream(previewStreamData, *videoPreview, std::make_shared<MediaStreamSubject>(mediaMap)); // Receive if (auto& videoReceive = videoRtp->getVideoReceive()) createCallAVStream(receiveStreamData, *videoReceive, std::make_shared<MediaStreamSubject>(mediaMap)); } else { #endif auto audioRtp = std::static_pointer_cast<AudioRtpSession>(rtpSession); // Preview if (auto& localAudio = audioRtp->getAudioLocal()) createCallAVStream(previewStreamData, *localAudio, std::make_shared<MediaStreamSubject>(mediaMap)); // Receive if (auto& audioReceive = audioRtp->getAudioReceive()) createCallAVStream(receiveStreamData, (AVMediaStream&) *audioReceive, std::make_shared<MediaStreamSubject>(mediaMap)); #ifdef ENABLE_VIDEO } #endif } } void SIPCall::createCallAVStream(const StreamData& StreamData, AVMediaStream& streamSource, const std::shared_ptr<MediaStreamSubject>& mediaStreamSubject) { const std::string AVStreamId = StreamData.id + std::to_string(static_cast<int>(StreamData.type)) + std::to_string(StreamData.direction); std::lock_guard lk(avStreamsMtx_); auto it = callAVStreams.find(AVStreamId); if (it != callAVStreams.end()) return; it = callAVStreams.insert(it, {AVStreamId, mediaStreamSubject}); streamSource.attachPriorityObserver(it->second); jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .createAVSubject(StreamData, it->second); } void SIPCall::clearCallAVStreams() { std::lock_guard lk(avStreamsMtx_); callAVStreams.clear(); } #endif // ENABLE_PLUGIN void SIPCall::setCallMediaLocal() { if (localAudioPort_ == 0 #ifdef ENABLE_VIDEO || localVideoPort_ == 0 #endif ) generateMediaPorts(); } void SIPCall::generateMediaPorts() { auto account = getSIPAccount(); if (!account) { JAMI_ERR("No account detected"); return; } // TODO. Setting specfic range for RTP ports is obsolete, in // particular in the context of ICE. // Reference: http://www.cs.columbia.edu/~hgs/rtp/faq.html#ports // We only want to set ports to new values if they haven't been set const unsigned callLocalAudioPort = account->generateAudioPort(); if (localAudioPort_ != 0) account->releasePort(localAudioPort_); localAudioPort_ = callLocalAudioPort; sdp_->setLocalPublishedAudioPorts(callLocalAudioPort, rtcpMuxEnabled_ ? 0 : callLocalAudioPort + 1); #ifdef ENABLE_VIDEO // https://projects.savoirfairelinux.com/issues/17498 const unsigned int callLocalVideoPort = account->generateVideoPort(); if (localVideoPort_ != 0) account->releasePort(localVideoPort_); // this should already be guaranteed by SIPAccount assert(localAudioPort_ != callLocalVideoPort); localVideoPort_ = callLocalVideoPort; sdp_->setLocalPublishedVideoPorts(callLocalVideoPort, rtcpMuxEnabled_ ? 0 : callLocalVideoPort + 1); #endif } const std::string& SIPCall::getContactHeader() const { return contactHeader_; } void SIPCall::setSipTransport(const std::shared_ptr<SipTransport>& transport, const std::string& contactHdr) { if (transport != sipTransport_) { JAMI_DBG("[call:%s] Setting transport to [%p]", getCallId().c_str(), transport.get()); } sipTransport_ = transport; contactHeader_ = contactHdr; if (not transport) { // Done. return; } if (contactHeader_.empty()) { JAMI_WARN("[call:%s] Contact header is empty", getCallId().c_str()); } if (isSrtpEnabled() and not sipTransport_->isSecure()) { JAMI_WARN("[call:%s] Crypto (SRTP) is negotiated over an un-encrypted signaling channel", getCallId().c_str()); } if (not isSrtpEnabled() and sipTransport_->isSecure()) { JAMI_WARN("[call:%s] The signaling channel is encrypted but the media is not encrypted", getCallId().c_str()); } const auto list_id = reinterpret_cast<uintptr_t>(this); sipTransport_->removeStateListener(list_id); // listen for transport destruction sipTransport_->addStateListener( list_id, [wthis_ = weak()](pjsip_transport_state state, const pjsip_transport_state_info*) { if (auto this_ = wthis_.lock()) { JAMI_DBG("[call:%s] SIP transport state [%i] - connection state [%u]", this_->getCallId().c_str(), state, static_cast<unsigned>(this_->getConnectionState())); // End the call if the SIP transport was shut down auto isAlive = SipTransport::isAlive(state); if (not isAlive and this_->getConnectionState() != ConnectionState::DISCONNECTED) { JAMI_WARN("[call:%s] Ending call because underlying SIP transport was closed", this_->getCallId().c_str()); this_->stopAllMedia(); this_->detachAudioFromConference(); this_->onFailure(ECONNRESET); } } }); } void SIPCall::requestReinvite(const std::vector<MediaAttribute>& mediaAttrList, bool needNewIce) { JAMI_DBG("[call:%s] Sending a SIP re-invite to request media change", getCallId().c_str()); if (isWaitingForIceAndMedia_) { remainingRequest_ = Request::SwitchInput; } else { if (SIPSessionReinvite(mediaAttrList, needNewIce) == PJ_SUCCESS and reinvIceMedia_) { isWaitingForIceAndMedia_ = true; } } } /** * Send a reINVITE inside an active dialog to modify its state * Local SDP session should be modified before calling this method */ int SIPCall::SIPSessionReinvite(const std::vector<MediaAttribute>& mediaAttrList, bool needNewIce) { assert(not mediaAttrList.empty()); std::lock_guard lk {callMutex_}; // Do nothing if no invitation processed yet if (not inviteSession_ or inviteSession_->invite_tsx) return PJ_SUCCESS; JAMI_DBG("[call:%s] Preparing and sending a re-invite (state=%s)", getCallId().c_str(), pjsip_inv_state_name(inviteSession_->state)); JAMI_DBG("[call:%s] New ICE required for this re-invite: [%s]", getCallId().c_str(), needNewIce ? "Yes" : "No"); // Generate new ports to receive the new media stream // LibAV doesn't discriminate SSRCs and will be confused about Seq changes on a given port generateMediaPorts(); sdp_->clearIce(); sdp_->setActiveRemoteSdpSession(nullptr); sdp_->setActiveLocalSdpSession(nullptr); auto acc = getSIPAccount(); if (not acc) { JAMI_ERR("No account detected"); return !PJ_SUCCESS; } if (not sdp_->createOffer(mediaAttrList)) return !PJ_SUCCESS; if (isIceEnabled() and needNewIce) { if (not createIceMediaTransport(true) or not initIceMediaTransport(true)) { return !PJ_SUCCESS; } addLocalIceAttributes(); // Media transport changed, must restart the media. mediaRestartRequired_ = true; } pjsip_tx_data* tdata; auto local_sdp = sdp_->getLocalSdpSession(); auto result = pjsip_inv_reinvite(inviteSession_.get(), nullptr, local_sdp, &tdata); if (result == PJ_SUCCESS) { if (!tdata) return PJ_SUCCESS; // Add user-agent header sip_utils::addUserAgentHeader(acc->getUserAgentName(), tdata); result = pjsip_inv_send_msg(inviteSession_.get(), tdata); if (result == PJ_SUCCESS) return PJ_SUCCESS; JAMI_ERR("[call:%s] Failed to send REINVITE msg (pjsip: %s)", getCallId().c_str(), sip_utils::sip_strerror(result).c_str()); // Canceling internals without sending (anyways the send has just failed!) pjsip_inv_cancel_reinvite(inviteSession_.get(), &tdata); } else JAMI_ERR("[call:%s] Failed to create REINVITE msg (pjsip: %s)", getCallId().c_str(), sip_utils::sip_strerror(result).c_str()); return !PJ_SUCCESS; } int SIPCall::SIPSessionReinvite() { auto mediaList = getMediaAttributeList(); return SIPSessionReinvite(mediaList, isNewIceMediaRequired(mediaList)); } void SIPCall::sendSIPInfo(std::string_view body, std::string_view subtype) { std::lock_guard lk {callMutex_}; if (not inviteSession_ or not inviteSession_->dlg) throw VoipLinkException("Unable to get invite dialog"); constexpr pj_str_t methodName = CONST_PJ_STR("INFO"); constexpr pj_str_t type = CONST_PJ_STR("application"); pjsip_method method; pjsip_method_init_np(&method, (pj_str_t*) &methodName); /* Create request message. */ pjsip_tx_data* tdata; if (pjsip_dlg_create_request(inviteSession_->dlg, &method, -1, &tdata) != PJ_SUCCESS) { JAMI_ERR("[call:%s] Unable to create dialog", getCallId().c_str()); return; } /* Create "application/<subtype>" message body. */ pj_str_t content = CONST_PJ_STR(body); pj_str_t pj_subtype = CONST_PJ_STR(subtype); tdata->msg->body = pjsip_msg_body_create(tdata->pool, &type, &pj_subtype, &content); if (tdata->msg->body == NULL) pjsip_tx_data_dec_ref(tdata); else pjsip_dlg_send_request(inviteSession_->dlg, tdata, Manager::instance().sipVoIPLink().getModId(), NULL); } void SIPCall::updateRecState(bool state) { std::string BODY = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<media_control><vc_primitive><to_encoder>" "<recording_state=" + std::to_string(state) + "/>" "</to_encoder></vc_primitive></media_control>"; // see https://tools.ietf.org/html/rfc5168 for XML Schema for Media Control details JAMI_DBG("Sending recording state via SIP INFO"); try { sendSIPInfo(BODY, "media_control+xml"); } catch (const std::exception& e) { JAMI_ERR("Error sending recording state: %s", e.what()); } } void SIPCall::requestKeyframe(int streamIdx) { auto now = clock::now(); if ((now - lastKeyFrameReq_) < MS_BETWEEN_2_KEYFRAME_REQUEST and lastKeyFrameReq_ != time_point::min()) return; std::string streamIdPart; if (streamIdx != -1) streamIdPart = fmt::format("<stream_id>{}</stream_id>", streamIdx); std::string BODY = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<media_control><vc_primitive> " + streamIdPart + "<to_encoder>" + "<picture_fast_update/>" "</to_encoder></vc_primitive></media_control>"; JAMI_DBG("Sending video keyframe request via SIP INFO"); try { sendSIPInfo(BODY, "media_control+xml"); } catch (const std::exception& e) { JAMI_ERR("Error sending video keyframe request: %s", e.what()); } lastKeyFrameReq_ = now; } void SIPCall::sendMuteState(bool state) { std::string BODY = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<media_control><vc_primitive><to_encoder>" "<mute_state=" + std::to_string(state) + "/>" "</to_encoder></vc_primitive></media_control>"; // see https://tools.ietf.org/html/rfc5168 for XML Schema for Media Control details JAMI_DBG("Sending mute state via SIP INFO"); try { sendSIPInfo(BODY, "media_control+xml"); } catch (const std::exception& e) { JAMI_ERR("Error sending mute state: %s", e.what()); } } void SIPCall::sendVoiceActivity(std::string_view streamId, bool state) { // dont send streamId if it's -1 std::string streamIdPart = ""; if (streamId != "-1" && !streamId.empty()) { streamIdPart = fmt::format("<stream_id>{}</stream_id>", streamId); } std::string BODY = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<media_control><vc_primitive>" + streamIdPart + "<to_encoder>" "<voice_activity=" + std::to_string(state) + "/>" "</to_encoder></vc_primitive></media_control>"; try { sendSIPInfo(BODY, "media_control+xml"); } catch (const std::exception& e) { JAMI_ERR("Error sending voice activity state: %s", e.what()); } } void SIPCall::setInviteSession(pjsip_inv_session* inviteSession) { std::lock_guard lk {callMutex_}; if (inviteSession == nullptr and inviteSession_) { JAMI_DBG("[call:%s] Delete current invite session", getCallId().c_str()); } else if (inviteSession != nullptr) { // NOTE: The first reference of the invite session is owned by pjsip. If // that counter goes down to zero the invite will be destroyed, and the // unique_ptr will point freed datas. To avoid this, we increment the // ref counter and let our unique_ptr share the ownership of the session // with pjsip. if (PJ_SUCCESS != pjsip_inv_add_ref(inviteSession)) { JAMI_WARN("[call:%s] Attempting to set invalid invite session [%p]", getCallId().c_str(), inviteSession); inviteSession_.reset(nullptr); return; } JAMI_DBG("[call:%s] Set new invite session [%p]", getCallId().c_str(), inviteSession); } else { // Nothing to do. return; } inviteSession_.reset(inviteSession); } void SIPCall::terminateSipSession(int status) { JAMI_DBG("[call:%s] Terminate SIP session", getCallId().c_str()); std::lock_guard lk {callMutex_}; if (inviteSession_ and inviteSession_->state != PJSIP_INV_STATE_DISCONNECTED) { pjsip_tx_data* tdata = nullptr; auto ret = pjsip_inv_end_session(inviteSession_.get(), status, nullptr, &tdata); if (ret == PJ_SUCCESS) { if (tdata) { auto account = getSIPAccount(); if (account) { sip_utils::addContactHeader(contactHeader_, tdata); // Add user-agent header sip_utils::addUserAgentHeader(account->getUserAgentName(), tdata); } else { JAMI_ERR("No account detected"); std::ostringstream msg; msg << "[call:" << getCallId().c_str() << "] " << "The account owning this call is invalid"; throw std::runtime_error(msg.str()); } ret = pjsip_inv_send_msg(inviteSession_.get(), tdata); if (ret != PJ_SUCCESS) JAMI_ERR("[call:%s] Failed to send terminate msg, SIP error (%s)", getCallId().c_str(), sip_utils::sip_strerror(ret).c_str()); } } else JAMI_ERR("[call:%s] Failed to terminate INVITE@%p, SIP error (%s)", getCallId().c_str(), inviteSession_.get(), sip_utils::sip_strerror(ret).c_str()); } setInviteSession(); } void SIPCall::answer() { std::lock_guard lk {callMutex_}; auto account = getSIPAccount(); if (!account) { JAMI_ERR("No account detected"); return; } if (not inviteSession_) throw VoipLinkException("[call:" + getCallId() + "] Answer: no invite session for this call"); if (!inviteSession_->neg) { JAMI_WARN("[call:%s] Negotiator is NULL, we've received an INVITE without an SDP", getCallId().c_str()); Manager::instance().sipVoIPLink().createSDPOffer(inviteSession_.get()); } pjsip_tx_data* tdata; if (!inviteSession_->last_answer) throw std::runtime_error("Should only be called for initial answer"); // answer with SDP if no SDP was given in initial invite (i.e. inv->neg is NULL) if (pjsip_inv_answer(inviteSession_.get(), PJSIP_SC_OK, NULL, !inviteSession_->neg ? sdp_->getLocalSdpSession() : NULL, &tdata) != PJ_SUCCESS) throw std::runtime_error("Unable to init invite request answer (200 OK)"); if (contactHeader_.empty()) { throw std::runtime_error("Unable to answer with an invalid contact header"); } JAMI_DBG("[call:%s] Answering with contact header: %s", getCallId().c_str(), contactHeader_.c_str()); sip_utils::addContactHeader(contactHeader_, tdata); // Add user-agent header sip_utils::addUserAgentHeader(account->getUserAgentName(), tdata); if (pjsip_inv_send_msg(inviteSession_.get(), tdata) != PJ_SUCCESS) { setInviteSession(); throw std::runtime_error("Unable to send invite request answer (200 OK)"); } setState(CallState::ACTIVE, ConnectionState::CONNECTED); } void SIPCall::answer(const std::vector<libjami::MediaMap>& mediaList) { std::lock_guard lk {callMutex_}; auto account = getSIPAccount(); if (not account) { JAMI_ERR("No account detected"); return; } if (not inviteSession_) { JAMI_ERR("[call:%s] No invite session for this call", getCallId().c_str()); return; } if (not sdp_) { JAMI_ERR("[call:%s] No SDP session for this call", getCallId().c_str()); return; } auto newMediaAttrList = MediaAttribute::buildMediaAttributesList(mediaList, isSrtpEnabled()); if (newMediaAttrList.empty() and rtpStreams_.empty()) { JAMI_ERR("[call:%s] Media list must not be empty!", getCallId().c_str()); return; } // If the media list is empty, use the current media (this could happen // with auto-answer for instance), otherwise update the current media. if (newMediaAttrList.empty()) { JAMI_DBG("[call:%s] Media list is empty, using current media", getCallId().c_str()); } else if (newMediaAttrList.size() != rtpStreams_.size()) { // Media count is not expected to change JAMI_ERROR("[call:{:s}] Media list size {:d} in answer does not match. Expected {:d}", getCallId(), newMediaAttrList.size(), rtpStreams_.size()); return; } auto const& mediaAttrList = newMediaAttrList.empty() ? getMediaAttributeList() : newMediaAttrList; JAMI_DBG("[call:%s] Answering incoming call with following media:", getCallId().c_str()); for (size_t idx = 0; idx < mediaAttrList.size(); idx++) { auto const& mediaAttr = mediaAttrList.at(idx); JAMI_DEBUG("[call:{:s}] Media @{:d} - {:s}", getCallId(), idx, mediaAttr.toString(true)); } // Apply the media attributes. for (size_t idx = 0; idx < mediaAttrList.size(); idx++) { updateMediaStream(mediaAttrList[idx], idx); } // Create the SDP answer sdp_->processIncomingOffer(mediaAttrList); if (isIceEnabled() and remoteHasValidIceAttributes()) { setupIceResponse(); } if (not inviteSession_->neg) { // We are answering to an INVITE that did not include a media offer (SDP). // The SIP specification (RFCs 3261/6337) requires that if a UA wishes to // proceed with the call, it must provide a media offer (SDP) if the initial // INVITE did not offer one. In this case, the SDP offer will be included in // the SIP OK (200) answer. The peer UA will then include its SDP answer in // the SIP ACK message. // TODO. This code should be unified with the code used by accounts to create // SDP offers. JAMI_WARN("[call:%s] No negotiator session, peer sent an empty INVITE (without SDP)", getCallId().c_str()); Manager::instance().sipVoIPLink().createSDPOffer(inviteSession_.get()); generateMediaPorts(); // Setup and create ICE offer if (isIceEnabled()) { sdp_->clearIce(); sdp_->setActiveRemoteSdpSession(nullptr); sdp_->setActiveLocalSdpSession(nullptr); auto opts = account->getIceOptions(); auto publicAddr = account->getPublishedIpAddress(); if (publicAddr) { opts.accountPublicAddr = publicAddr; if (auto interfaceAddr = dhtnet::ip_utils::getInterfaceAddr(account->getLocalInterface(), publicAddr.getFamily())) { opts.accountLocalAddr = interfaceAddr; if (createIceMediaTransport(false) and initIceMediaTransport(true, std::move(opts))) { addLocalIceAttributes(); } } else { JAMI_WARN("[call:%s] Unable to init ICE transport, missing local address", getCallId().c_str()); } } else { JAMI_WARN("[call:%s] Unable to init ICE transport, missing public address", getCallId().c_str()); } } } if (!inviteSession_->last_answer) throw std::runtime_error("Should only be called for initial answer"); // Set the SIP final answer (200 OK). pjsip_tx_data* tdata; if (pjsip_inv_answer(inviteSession_.get(), PJSIP_SC_OK, NULL, sdp_->getLocalSdpSession(), &tdata) != PJ_SUCCESS) throw std::runtime_error("Unable to init invite request answer (200 OK)"); if (contactHeader_.empty()) { throw std::runtime_error("Unable to answer with an invalid contact header"); } JAMI_DBG("[call:%s] Answering with contact header: %s", getCallId().c_str(), contactHeader_.c_str()); sip_utils::addContactHeader(contactHeader_, tdata); // Add user-agent header sip_utils::addUserAgentHeader(account->getUserAgentName(), tdata); if (pjsip_inv_send_msg(inviteSession_.get(), tdata) != PJ_SUCCESS) { setInviteSession(); throw std::runtime_error("Unable to send invite request answer (200 OK)"); } setState(CallState::ACTIVE, ConnectionState::CONNECTED); } void SIPCall::answerMediaChangeRequest(const std::vector<libjami::MediaMap>& mediaList, bool isRemote) { std::lock_guard lk {callMutex_}; auto account = getSIPAccount(); if (not account) { JAMI_ERR("[call:%s] No account detected", getCallId().c_str()); return; } auto mediaAttrList = MediaAttribute::buildMediaAttributesList(mediaList, isSrtpEnabled()); // TODO. is the right place? // Disable video if disabled in the account. if (not account->isVideoEnabled()) { for (auto& mediaAttr : mediaAttrList) { if (mediaAttr.type_ == MediaType::MEDIA_VIDEO) { mediaAttr.enabled_ = false; } } } if (mediaAttrList.empty()) { JAMI_WARN("[call:%s] Media list is empty. Ignoring the media change request", getCallId().c_str()); return; } if (not sdp_) { JAMI_ERR("[call:%s] No valid SDP session", getCallId().c_str()); return; } JAMI_DBG("[call:%s] Current media", getCallId().c_str()); unsigned idx = 0; for (auto const& rtp : rtpStreams_) { JAMI_DBG("[call:%s] Media @%u: %s", getCallId().c_str(), idx++, rtp.mediaAttribute_->toString(true).c_str()); } JAMI_DBG("[call:%s] Answering to media change request with new media", getCallId().c_str()); idx = 0; for (auto const& newMediaAttr : mediaAttrList) { JAMI_DBG("[call:%s] Media @%u: %s", getCallId().c_str(), idx++, newMediaAttr.toString(true).c_str()); } if (!updateAllMediaStreams(mediaAttrList, isRemote)) return; if (not sdp_->processIncomingOffer(mediaAttrList)) { JAMI_WARN("[call:%s] Unable to process the new offer, ignoring", getCallId().c_str()); return; } if (not sdp_->getRemoteSdpSession()) { JAMI_ERR("[call:%s] No valid remote SDP session", getCallId().c_str()); return; } if (isIceEnabled() and remoteHasValidIceAttributes()) { JAMI_WARN("[call:%s] Requesting a new ICE media", getCallId().c_str()); setupIceResponse(true); } if (not sdp_->startNegotiation()) { JAMI_ERR("[call:%s] Unable to start media negotiation for a re-invite request", getCallId().c_str()); return; } if (pjsip_inv_set_sdp_answer(inviteSession_.get(), sdp_->getLocalSdpSession()) != PJ_SUCCESS) { JAMI_ERR("[call:%s] Unable to start media negotiation for a re-invite request", getCallId().c_str()); return; } pjsip_tx_data* tdata; if (pjsip_inv_answer(inviteSession_.get(), PJSIP_SC_OK, NULL, NULL, &tdata) != PJ_SUCCESS) { JAMI_ERR("[call:%s] Unable to init answer to a re-invite request", getCallId().c_str()); return; } if (not contactHeader_.empty()) { sip_utils::addContactHeader(contactHeader_, tdata); } // Add user-agent header sip_utils::addUserAgentHeader(account->getUserAgentName(), tdata); if (pjsip_inv_send_msg(inviteSession_.get(), tdata) != PJ_SUCCESS) { JAMI_ERR("[call:%s] Unable to send answer to a re-invite request", getCallId().c_str()); setInviteSession(); return; } JAMI_DBG("[call:%s] Successfully answered the media change request", getCallId().c_str()); } void SIPCall::hangup(int reason) { std::lock_guard lk {callMutex_}; pendingRecord_ = false; if (inviteSession_ and inviteSession_->dlg) { pjsip_route_hdr* route = inviteSession_->dlg->route_set.next; while (route and route != &inviteSession_->dlg->route_set) { char buf[1024]; int printed = pjsip_hdr_print_on(route, buf, sizeof(buf)); if (printed >= 0) { buf[printed] = '\0'; JAMI_DBG("[call:%s] Route header %s", getCallId().c_str(), buf); } route = route->next; } int status = PJSIP_SC_OK; if (reason) status = reason; else if (inviteSession_->state <= PJSIP_INV_STATE_EARLY and inviteSession_->role != PJSIP_ROLE_UAC) status = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; else if (inviteSession_->state >= PJSIP_INV_STATE_DISCONNECTED) status = PJSIP_SC_DECLINE; // Notify the peer terminateSipSession(status); } // Stop all RTP streams stopAllMedia(); detachAudioFromConference(); setState(Call::ConnectionState::DISCONNECTED, reason); dht::ThreadPool::io().run([w = weak()] { if (auto shared = w.lock()) shared->removeCall(); }); } void SIPCall::detachAudioFromConference() { #ifdef ENABLE_VIDEO if (auto conf = getConference()) { if (auto mixer = conf->getVideoMixer()) { for (auto& stream : getRtpSessionList(MediaType::MEDIA_AUDIO)) { mixer->removeAudioOnlySource(getCallId(), stream->streamId()); } } } #endif } void SIPCall::refuse() { if (!isIncoming() or getConnectionState() == ConnectionState::CONNECTED or !inviteSession_) return; stopAllMedia(); // Notify the peer terminateSipSession(PJSIP_SC_DECLINE); setState(Call::ConnectionState::DISCONNECTED, ECONNABORTED); removeCall(); } static void transfer_client_cb(pjsip_evsub* sub, pjsip_event* event) { auto mod_ua_id = Manager::instance().sipVoIPLink().getModId(); switch (pjsip_evsub_get_state(sub)) { case PJSIP_EVSUB_STATE_ACCEPTED: if (!event) return; pj_assert(event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG); break; case PJSIP_EVSUB_STATE_TERMINATED: pjsip_evsub_set_mod_data(sub, mod_ua_id, NULL); break; case PJSIP_EVSUB_STATE_ACTIVE: { if (!event) return; pjsip_rx_data* r_data = event->body.rx_msg.rdata; if (!r_data) return; std::string request(pjsip_rx_data_get_info(r_data)); pjsip_status_line status_line = {500, *pjsip_get_status_text(500)}; if (!r_data->msg_info.msg) return; if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD and request.find("NOTIFY") != std::string::npos) { pjsip_msg_body* body = r_data->msg_info.msg->body; if (!body) return; if (pj_stricmp2(&body->content_type.type, "message") or pj_stricmp2(&body->content_type.subtype, "sipfrag")) return; if (pjsip_parse_status_line((char*) body->data, body->len, &status_line) != PJ_SUCCESS) return; } if (!r_data->msg_info.cid) return; auto call = static_cast<SIPCall*>(pjsip_evsub_get_mod_data(sub, mod_ua_id)); if (!call) return; if (status_line.code / 100 == 2) { if (call->inviteSession_) call->terminateSipSession(PJSIP_SC_GONE); Manager::instance().hangupCall(call->getAccountId(), call->getCallId()); pjsip_evsub_set_mod_data(sub, mod_ua_id, NULL); } break; } case PJSIP_EVSUB_STATE_NULL: case PJSIP_EVSUB_STATE_SENT: case PJSIP_EVSUB_STATE_PENDING: case PJSIP_EVSUB_STATE_UNKNOWN: default: break; } } bool SIPCall::transferCommon(const pj_str_t* dst) { if (not inviteSession_ or not inviteSession_->dlg) return false; pjsip_evsub_user xfer_cb; pj_bzero(&xfer_cb, sizeof(xfer_cb)); xfer_cb.on_evsub_state = &transfer_client_cb; pjsip_evsub* sub; if (pjsip_xfer_create_uac(inviteSession_->dlg, &xfer_cb, &sub) != PJ_SUCCESS) return false; /* Associate this voiplink of call with the client subscription * We are unable to just associate call with the client subscription * because after this function, we are unable to find the corresponding * voiplink from the call any more. But the voiplink is useful! */ pjsip_evsub_set_mod_data(sub, Manager::instance().sipVoIPLink().getModId(), this); /* * Create REFER request. */ pjsip_tx_data* tdata; if (pjsip_xfer_initiate(sub, dst, &tdata) != PJ_SUCCESS) return false; /* Send. */ if (pjsip_xfer_send_request(sub, tdata) != PJ_SUCCESS) return false; return true; } void SIPCall::transfer(const std::string& to) { auto account = getSIPAccount(); if (!account) { JAMI_ERR("No account detected"); return; } deinitRecorder(); if (Call::isRecording()) stopRecording(); std::string toUri = account->getToUri(to); const pj_str_t dst(CONST_PJ_STR(toUri)); JAMI_DBG("[call:%s] Transferring to %.*s", getCallId().c_str(), (int) dst.slen, dst.ptr); if (!transferCommon(&dst)) throw VoipLinkException("Unable to transfer"); } bool SIPCall::attendedTransfer(const std::string& to) { auto toCall = Manager::instance().callFactory.getCall<SIPCall>(to); if (!toCall) return false; if (not toCall->inviteSession_ or not toCall->inviteSession_->dlg) return false; pjsip_dialog* target_dlg = toCall->inviteSession_->dlg; pjsip_uri* uri = (pjsip_uri*) pjsip_uri_get_uri(target_dlg->remote.info->uri); char str_dest_buf[PJSIP_MAX_URL_SIZE * 2] = {'<'}; pj_str_t dst = {str_dest_buf, 1}; dst.slen += pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, str_dest_buf + 1, sizeof(str_dest_buf) - 1); dst.slen += pj_ansi_snprintf(str_dest_buf + dst.slen, sizeof(str_dest_buf) - dst.slen, "?" "Replaces=%.*s" "%%3Bto-tag%%3D%.*s" "%%3Bfrom-tag%%3D%.*s>", (int) target_dlg->call_id->id.slen, target_dlg->call_id->id.ptr, (int) target_dlg->remote.info->tag.slen, target_dlg->remote.info->tag.ptr, (int) target_dlg->local.info->tag.slen, target_dlg->local.info->tag.ptr); return transferCommon(&dst); } bool SIPCall::onhold(OnReadyCb&& cb) { // If ICE is currently negotiating, we must wait before hold the call if (isWaitingForIceAndMedia_) { holdCb_ = std::move(cb); remainingRequest_ = Request::HoldingOn; return false; } auto result = hold(); if (cb) cb(result); return result; } bool SIPCall::hold() { if (getConnectionState() != ConnectionState::CONNECTED) { JAMI_WARN("[call:%s] Not connected, ignoring hold request", getCallId().c_str()); return false; } if (not setState(CallState::HOLD)) { JAMI_WARN("[call:%s] Failed to set state to HOLD", getCallId().c_str()); return false; } stopAllMedia(); for (auto& stream : rtpStreams_) { stream.mediaAttribute_->onHold_ = true; } if (SIPSessionReinvite() != PJ_SUCCESS) { JAMI_WARN("[call:%s] Reinvite failed", getCallId().c_str()); return false; } // TODO. Do we need to check for reinvIceMedia_ ? isWaitingForIceAndMedia_ = (reinvIceMedia_ != nullptr); JAMI_DBG("[call:%s] Set state to HOLD", getCallId().c_str()); return true; } bool SIPCall::offhold(OnReadyCb&& cb) { // If ICE is currently negotiating, we must wait before unhold the call if (isWaitingForIceAndMedia_) { JAMI_DBG("[call:%s] ICE negotiation in progress. Resume request will be once ICE " "negotiation completes", getCallId().c_str()); offHoldCb_ = std::move(cb); remainingRequest_ = Request::HoldingOff; return false; } JAMI_DBG("[call:%s] Resuming the call", getCallId().c_str()); auto result = unhold(); if (cb) cb(result); return result; } bool SIPCall::unhold() { auto account = getSIPAccount(); if (!account) { JAMI_ERR("No account detected"); return false; } bool success = false; try { success = internalOffHold([] {}); } catch (const SdpException& e) { JAMI_ERR("[call:%s] %s", getCallId().c_str(), e.what()); throw VoipLinkException("SDP issue in offhold"); } // Only wait for ICE if we have an ICE re-invite in progress isWaitingForIceAndMedia_ = success and (reinvIceMedia_ != nullptr); return success; } bool SIPCall::internalOffHold(const std::function<void()>& sdp_cb) { if (getConnectionState() != ConnectionState::CONNECTED) { JAMI_WARN("[call:%s] Not connected, ignoring resume request", getCallId().c_str()); } if (not setState(CallState::ACTIVE)) return false; sdp_cb(); { for (auto& stream : rtpStreams_) { stream.mediaAttribute_->onHold_ = false; } // For now, call resume will always require new ICE negotiation. if (SIPSessionReinvite(getMediaAttributeList(), true) != PJ_SUCCESS) { JAMI_WARN("[call:%s] Resuming hold", getCallId().c_str()); if (isWaitingForIceAndMedia_) { remainingRequest_ = Request::HoldingOn; } else { hold(); } return false; } } return true; } void SIPCall::switchInput(const std::string& source) { JAMI_DBG("[call:%s] Set selected source to %s", getCallId().c_str(), source.c_str()); for (auto const& stream : rtpStreams_) { auto mediaAttr = stream.mediaAttribute_; mediaAttr->sourceUri_ = source; } // Check if the call is being recorded in order to continue // ... the recording after the switch bool isRec = Call::isRecording(); if (isWaitingForIceAndMedia_) { remainingRequest_ = Request::SwitchInput; } else { // For now, switchInput will always trigger a re-invite // with new ICE session. if (SIPSessionReinvite(getMediaAttributeList(), true) == PJ_SUCCESS and reinvIceMedia_) { isWaitingForIceAndMedia_ = true; } } if (isRec) { readyToRecord_ = false; pendingRecord_ = true; } } void SIPCall::peerHungup() { pendingRecord_ = false; // Stop all RTP streams stopAllMedia(); if (inviteSession_) terminateSipSession(PJSIP_SC_NOT_FOUND); detachAudioFromConference(); Call::peerHungup(); } void SIPCall::carryingDTMFdigits(char code) { int duration = Manager::instance().voipPreferences.getPulseLength(); char dtmf_body[1000]; int ret; // handle flash code if (code == '!') { ret = snprintf(dtmf_body, sizeof dtmf_body - 1, "Signal=16\r\nDuration=%d\r\n", duration); } else { ret = snprintf(dtmf_body, sizeof dtmf_body - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration); } try { sendSIPInfo({dtmf_body, (size_t) ret}, "dtmf-relay"); } catch (const std::exception& e) { JAMI_ERR("Error sending DTMF: %s", e.what()); } } void SIPCall::setVideoOrientation(int streamIdx, int rotation) { std::string streamIdPart; if (streamIdx != -1) streamIdPart = fmt::format("<stream_id>{}</stream_id>", streamIdx); std::string sip_body = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<media_control><vc_primitive><to_encoder>" "<device_orientation=" + std::to_string(-rotation) + "/>" + "</to_encoder>" + streamIdPart + "</vc_primitive></media_control>"; JAMI_DBG("Sending device orientation via SIP INFO %d for stream %u", rotation, streamIdx); sendSIPInfo(sip_body, "media_control+xml"); } void SIPCall::sendTextMessage(const std::map<std::string, std::string>& messages, const std::string& from) { // TODO: for now we ignore the "from" (the previous implementation for sending this info was // buggy and verbose), another way to send the original message sender will be implemented // in the future if (not subcalls_.empty()) { pendingOutMessages_.emplace_back(messages, from); for (auto& c : subcalls_) c->sendTextMessage(messages, from); } else { if (inviteSession_) { try { // Ignore if the peer does not allow "MESSAGE" SIP method // NOTE: // The SIP "Allow" header is not mandatory as per RFC-3261. If it's // not present and since "MESSAGE" method is an extention method, // we choose to assume that the peer does not support the "MESSAGE" // method to prevent unexpected behavior when interoperating with // some SIP implementations. if (not isSipMethodAllowedByPeer(sip_utils::SIP_METHODS::MESSAGE)) { JAMI_WARN() << fmt::format("[call:{}] Peer does not allow \"{}\" method", getCallId(), sip_utils::SIP_METHODS::MESSAGE); // Print peer's allowed methods JAMI_INFO() << fmt::format("[call:{}] Peer's allowed methods: {}", getCallId(), peerAllowedMethods_); return; } im::sendSipMessage(inviteSession_.get(), messages); } catch (...) { JAMI_ERR("[call:%s] Failed to send SIP text message", getCallId().c_str()); } } else { pendingOutMessages_.emplace_back(messages, from); JAMI_ERR("[call:%s] sendTextMessage: no invite session for this call", getCallId().c_str()); } } } void SIPCall::removeCall() { #ifdef ENABLE_PLUGIN jami::Manager::instance().getJamiPluginManager().getCallServicesManager().clearCallHandlerMaps( getCallId()); #endif std::lock_guard lk {callMutex_}; JAMI_DBG("[call:%s] removeCall()", getCallId().c_str()); if (sdp_) { sdp_->setActiveLocalSdpSession(nullptr); sdp_->setActiveRemoteSdpSession(nullptr); } Call::removeCall(); { std::lock_guard lk(transportMtx_); resetTransport(std::move(iceMedia_)); resetTransport(std::move(reinvIceMedia_)); } setInviteSession(); setSipTransport({}); } void SIPCall::onFailure(signed cause) { if (setState(CallState::MERROR, ConnectionState::DISCONNECTED, cause)) { runOnMainThread([w = weak()] { if (auto shared = w.lock()) { auto& call = *shared; Manager::instance().callFailure(call); call.removeCall(); } }); } } void SIPCall::onBusyHere() { if (getCallType() == CallType::OUTGOING) setState(CallState::PEER_BUSY, ConnectionState::DISCONNECTED); else setState(CallState::BUSY, ConnectionState::DISCONNECTED); runOnMainThread([w = weak()] { if (auto shared = w.lock()) { auto& call = *shared; Manager::instance().callBusy(call); call.removeCall(); } }); } void SIPCall::onClosed() { runOnMainThread([w = weak()] { if (auto shared = w.lock()) { auto& call = *shared; Manager::instance().peerHungupCall(call); call.removeCall(); } }); } void SIPCall::onAnswered() { JAMI_WARN("[call:%s] onAnswered()", getCallId().c_str()); runOnMainThread([w = weak()] { if (auto shared = w.lock()) { if (shared->getConnectionState() != ConnectionState::CONNECTED) { shared->setState(CallState::ACTIVE, ConnectionState::CONNECTED); if (not shared->isSubcall()) { Manager::instance().peerAnsweredCall(*shared); } } } }); } void SIPCall::sendKeyframe(int streamIdx) { #ifdef ENABLE_VIDEO dht::ThreadPool::computation().run([w = weak(), streamIdx] { if (auto sthis = w.lock()) { JAMI_DBG("handling picture fast update request"); if (streamIdx == -1) { for (const auto& videoRtp : sthis->getRtpSessionList(MediaType::MEDIA_VIDEO)) std::static_pointer_cast<video::VideoRtpSession>(videoRtp)->forceKeyFrame(); } else if (streamIdx > -1 && streamIdx < static_cast<int>(sthis->rtpStreams_.size())) { // Apply request for wanted stream auto& stream = sthis->rtpStreams_[streamIdx]; if (stream.rtpSession_ && stream.rtpSession_->getMediaType() == MediaType::MEDIA_VIDEO) std::static_pointer_cast<video::VideoRtpSession>(stream.rtpSession_) ->forceKeyFrame(); } } }); #endif } bool SIPCall::isIceEnabled() const { return enableIce_; } void SIPCall::setPeerUaVersion(std::string_view ua) { if (peerUserAgent_ == ua or ua.empty()) { // Silently ignore if it did not change or empty. return; } if (peerUserAgent_.empty()) { JAMI_DEBUG("[call:{}] Set peer's User-Agent to [{}]", getCallId(), ua); } else if (not peerUserAgent_.empty()) { // Unlikely, but should be handled since we dont have control over the peer. // Even if it's unexpected, we still try to parse the UA version. JAMI_WARNING("[call:{}] Peer's User-Agent unexpectedly changed from [{}] to [{}]", getCallId(), peerUserAgent_, ua); } peerUserAgent_ = ua; // User-agent parsing constexpr std::string_view PACK_NAME(PACKAGE_NAME " "); auto pos = ua.find(PACK_NAME); if (pos == std::string_view::npos) { // Must have the expected package name. JAMI_WARN("Unable to find the expected package name in peer's User-Agent"); return; } ua = ua.substr(pos + PACK_NAME.length()); std::string_view version; // Unstable (un-released) versions has a hiphen + commit Id after // the version number. Find the commit Id if any, and ignore it. pos = ua.find('-'); if (pos != std::string_view::npos) { // Get the version and ignore the commit ID. version = ua.substr(0, pos); } else { // Extract the version number. pos = ua.find(' '); if (pos != std::string_view::npos) { version = ua.substr(0, pos); } } if (version.empty()) { JAMI_DEBUG("[call:{}] Unable to parse peer's version", getCallId()); return; } auto peerVersion = split_string_to_unsigned(version, '.'); if (peerVersion.size() > 4u) { JAMI_WARNING("[call:{}] Unable to parse peer's version", getCallId()); return; } // Check if peer's version is at least 10.0.2 to enable multi-stream. peerSupportMultiStream_ = Account::meetMinimumRequiredVersion(peerVersion, MULTISTREAM_REQUIRED_VERSION); if (not peerSupportMultiStream_) { JAMI_DEBUG( "Peer's version [{}] does not support multi-stream. Min required version: [{}]", version, MULTISTREAM_REQUIRED_VERSION_STR); } // Check if peer's version is at least 13.11.0 to enable multi-audio-stream. peerSupportMultiAudioStream_ = Account::meetMinimumRequiredVersion(peerVersion, MULTIAUDIO_REQUIRED_VERSION); if (not peerSupportMultiAudioStream_) { JAMI_DEBUG( "Peer's version [{}] does not support multi-audio-stream. Min required version: [{}]", version, MULTIAUDIO_REQUIRED_VERSION_STR); } // Check if peer's version is at least 13.3.0 to enable multi-ICE. peerSupportMultiIce_ = Account::meetMinimumRequiredVersion(peerVersion, MULTIICE_REQUIRED_VERSION); if (not peerSupportMultiIce_) { JAMI_DEBUG("Peer's version [{}] does not support more than 2 ICE medias. Min required " "version: [{}]", version, MULTIICE_REQUIRED_VERSION_STR); } // Check if peer's version supports re-invite without ICE renegotiation. peerSupportReuseIceInReinv_ = Account::meetMinimumRequiredVersion(peerVersion, REUSE_ICE_IN_REINVITE_REQUIRED_VERSION); if (not peerSupportReuseIceInReinv_) { JAMI_DEBUG("Peer's version [%.*s] does not support re-invite without ICE renegotiation. Min " "required version: [%.*s]", version, REUSE_ICE_IN_REINVITE_REQUIRED_VERSION_STR); } } void SIPCall::setPeerAllowMethods(std::vector<std::string> methods) { std::lock_guard lock {callMutex_}; peerAllowedMethods_ = std::move(methods); } bool SIPCall::isSipMethodAllowedByPeer(const std::string_view method) const { std::lock_guard lock {callMutex_}; return std::find(peerAllowedMethods_.begin(), peerAllowedMethods_.end(), method) != peerAllowedMethods_.end(); } void SIPCall::onPeerRinging() { JAMI_DBG("[call:%s] Peer ringing", getCallId().c_str()); setState(ConnectionState::RINGING); } void SIPCall::addLocalIceAttributes() { if (not isIceEnabled()) return; auto iceMedia = getIceMedia(); if (not iceMedia) { JAMI_ERR("[call:%s] Invalid ICE instance", getCallId().c_str()); return; } auto start = std::chrono::steady_clock::now(); if (not iceMedia->isInitialized()) { JAMI_DBG("[call:%s] Waiting for ICE initialization", getCallId().c_str()); // we need an initialized ICE to progress further if (iceMedia->waitForInitialization(DEFAULT_ICE_INIT_TIMEOUT) <= 0) { JAMI_ERR("[call:%s] ICE initialization timed out", getCallId().c_str()); return; } // ICE initialization may take longer than usual in some cases, // for instance when TURN servers do not respond in time (DNS // resolution or other issues). auto duration = std::chrono::steady_clock::now() - start; if (duration > EXPECTED_ICE_INIT_MAX_TIME) { JAMI_WARNING("[call:{:s}] ICE initialization time was unexpectedly high ({})", getCallId(), std::chrono::duration_cast<std::chrono::milliseconds>(duration)); } } // Check the state of ICE instance, the initialization may have failed. if (not iceMedia->isInitialized()) { JAMI_ERR("[call:%s] ICE session is not initialized", getCallId().c_str()); return; } // Check the state, the call might have been canceled while waiting. // for initialization. if (getState() == Call::CallState::OVER) { JAMI_WARN("[call:%s] The call was terminated while waiting for ICE initialization", getCallId().c_str()); return; } auto account = getSIPAccount(); if (not account) { JAMI_ERR("No account detected"); return; } if (not sdp_) { JAMI_ERR("No sdp detected"); return; } JAMI_DBG("[call:%s] Add local attributes for ICE instance [%p]", getCallId().c_str(), iceMedia.get()); sdp_->addIceAttributes(iceMedia->getLocalAttributes()); if (account->isIceCompIdRfc5245Compliant()) { unsigned streamIdx = 0; for (auto const& stream : rtpStreams_) { if (not stream.mediaAttribute_->enabled_) { // Dont add ICE candidates if the media is disabled JAMI_DBG("[call:%s] Media [%s] @ %u is disabled, dont add local candidates", getCallId().c_str(), stream.mediaAttribute_->toString().c_str(), streamIdx); continue; } JAMI_DBG("[call:%s] Add ICE local candidates for media [%s] @ %u", getCallId().c_str(), stream.mediaAttribute_->toString().c_str(), streamIdx); // RTP sdp_->addIceCandidates(streamIdx, iceMedia->getLocalCandidates(streamIdx, ICE_COMP_ID_RTP)); // RTCP if it has its own port if (not rtcpMuxEnabled_) { sdp_->addIceCandidates(streamIdx, iceMedia->getLocalCandidates(streamIdx, ICE_COMP_ID_RTP + 1)); } streamIdx++; } } else { unsigned idx = 0; unsigned compId = 1; for (auto const& stream : rtpStreams_) { if (not stream.mediaAttribute_->enabled_) { // Skipping local ICE candidates if the media is disabled continue; } JAMI_DBG("[call:%s] Add ICE local candidates for media [%s] @ %u", getCallId().c_str(), stream.mediaAttribute_->toString().c_str(), idx); // RTP sdp_->addIceCandidates(idx, iceMedia->getLocalCandidates(compId)); compId++; // RTCP if it has its own port if (not rtcpMuxEnabled_) { sdp_->addIceCandidates(idx, iceMedia->getLocalCandidates(compId)); compId++; } idx++; } } } std::vector<IceCandidate> SIPCall::getAllRemoteCandidates(dhtnet::IceTransport& transport) const { std::vector<IceCandidate> rem_candidates; for (unsigned mediaIdx = 0; mediaIdx < static_cast<unsigned>(rtpStreams_.size()); mediaIdx++) { IceCandidate cand; for (auto& line : sdp_->getIceCandidates(mediaIdx)) { if (transport.parseIceAttributeLine(mediaIdx, line, cand)) { JAMI_DBG("[call:%s] Add remote ICE candidate: %s", getCallId().c_str(), line.c_str()); rem_candidates.emplace_back(std::move(cand)); } } } return rem_candidates; } std::shared_ptr<SystemCodecInfo> SIPCall::getVideoCodec() const { #ifdef ENABLE_VIDEO // Return first video codec as we negotiate only one codec for the call // Note: with multistream we can negotiate codecs/stream, but it's not the case // in practice (same for audio), so just return the first video codec. for (const auto& videoRtp : getRtpSessionList(MediaType::MEDIA_VIDEO)) return videoRtp->getCodec(); #endif return {}; } std::shared_ptr<SystemCodecInfo> SIPCall::getAudioCodec() const { // Return first video codec as we negotiate only one codec for the call for (const auto& audioRtp : getRtpSessionList(MediaType::MEDIA_AUDIO)) return audioRtp->getCodec(); return {}; } void SIPCall::addMediaStream(const MediaAttribute& mediaAttr) { // Create and add the media stream with the provided attribute. // Do not create the RTP sessions yet. RtpStream stream; stream.mediaAttribute_ = std::make_shared<MediaAttribute>(mediaAttr); // Set default media source if empty. Kept for backward compatibility. #ifdef ENABLE_VIDEO if (stream.mediaAttribute_->sourceUri_.empty()) { stream.mediaAttribute_->sourceUri_ = Manager::instance().getVideoManager().videoDeviceMonitor.getMRLForDefaultDevice(); } #endif rtpStreams_.emplace_back(std::move(stream)); } size_t SIPCall::initMediaStreams(const std::vector<MediaAttribute>& mediaAttrList) { for (size_t idx = 0; idx < mediaAttrList.size(); idx++) { auto const& mediaAttr = mediaAttrList.at(idx); if (mediaAttr.type_ != MEDIA_AUDIO && mediaAttr.type_ != MEDIA_VIDEO) { JAMI_ERR("[call:%s] Unexpected media type %u", getCallId().c_str(), mediaAttr.type_); assert(false); } addMediaStream(mediaAttr); auto& stream = rtpStreams_.back(); createRtpSession(stream); JAMI_DEBUG("[call:{:s}] Added media @{:d}: {:s}", getCallId(), idx, stream.mediaAttribute_->toString(true)); } JAMI_DEBUG("[call:{:s}] Created {:d} Media streams", getCallId(), rtpStreams_.size()); return rtpStreams_.size(); } bool SIPCall::hasVideo() const { #ifdef ENABLE_VIDEO std::function<bool(const RtpStream& stream)> videoCheck = [](auto const& stream) { bool validVideo = stream.mediaAttribute_ && stream.mediaAttribute_->hasValidVideo(); bool validRemoteVideo = stream.remoteMediaAttribute_ && stream.remoteMediaAttribute_->hasValidVideo(); return validVideo || validRemoteVideo; }; const auto iter = std::find_if(rtpStreams_.begin(), rtpStreams_.end(), videoCheck); return iter != rtpStreams_.end(); #else return false; #endif } bool SIPCall::isCaptureDeviceMuted(const MediaType& mediaType) const { // Return true only if all media of type 'mediaType' that use capture devices // source, are muted. std::function<bool(const RtpStream& stream)> mutedCheck = [&mediaType](auto const& stream) { return (stream.mediaAttribute_->type_ == mediaType and not stream.mediaAttribute_->muted_); }; const auto iter = std::find_if(rtpStreams_.begin(), rtpStreams_.end(), mutedCheck); return iter == rtpStreams_.end(); } void SIPCall::setupNegotiatedMedia() { JAMI_DBG("[call:%s] Updating negotiated media", getCallId().c_str()); if (not sipTransport_ or not sdp_) { JAMI_ERR("[call:%s] Call is in an invalid state", getCallId().c_str()); return; } auto slots = sdp_->getMediaSlots(); bool peer_holding {true}; int streamIdx = -1; for (const auto& slot : slots) { streamIdx++; const auto& local = slot.first; const auto& remote = slot.second; // Skip disabled media if (not local.enabled) { JAMI_DBG("[call:%s] [SDP:slot#%u] The media is disabled, skipping", getCallId().c_str(), streamIdx); continue; } if (static_cast<size_t>(streamIdx) >= rtpStreams_.size()) { throw std::runtime_error("Stream index is out-of-range"); } auto const& rtpStream = rtpStreams_[streamIdx]; if (not rtpStream.mediaAttribute_) { throw std::runtime_error("Missing media attribute"); } // To enable a media, it must be enabled on both sides. rtpStream.mediaAttribute_->enabled_ = local.enabled and remote.enabled; if (not rtpStream.rtpSession_) throw std::runtime_error("Must have a valid RTP Session"); if (local.type != MEDIA_AUDIO && local.type != MEDIA_VIDEO) { JAMI_ERR("[call:%s] Unexpected media type %u", getCallId().c_str(), local.type); throw std::runtime_error("Invalid media attribute"); } if (local.type != remote.type) { JAMI_ERR("[call:%s] [SDP:slot#%u] Inconsistent media type between local and remote", getCallId().c_str(), streamIdx); continue; } if (local.enabled and not local.codec) { JAMI_WARN("[call:%s] [SDP:slot#%u] Missing local codec", getCallId().c_str(), streamIdx); continue; } if (remote.enabled and not remote.codec) { JAMI_WARN("[call:%s] [SDP:slot#%u] Missing remote codec", getCallId().c_str(), streamIdx); continue; } if (isSrtpEnabled() and local.enabled and not local.crypto) { JAMI_WARN("[call:%s] [SDP:slot#%u] Secure mode but no local crypto attributes. " "Ignoring the media", getCallId().c_str(), streamIdx); continue; } if (isSrtpEnabled() and remote.enabled and not remote.crypto) { JAMI_WARN("[call:%s] [SDP:slot#%u] Secure mode but no crypto remote attributes. " "Ignoring the media", getCallId().c_str(), streamIdx); continue; } // Aggregate holding info over all remote streams peer_holding &= remote.onHold; configureRtpSession(rtpStream.rtpSession_, rtpStream.mediaAttribute_, local, remote); } // TODO. Do we really use this? if (not isSubcall() and peerHolding_ != peer_holding) { peerHolding_ = peer_holding; emitSignal<libjami::CallSignal::PeerHold>(getCallId(), peerHolding_); } } void SIPCall::startAllMedia() { JAMI_DBG("[call:%s] Starting all media", getCallId().c_str()); if (not sipTransport_ or not sdp_) { JAMI_ERR("[call:%s] The call is in invalid state", getCallId().c_str()); return; } if (isSrtpEnabled() && not sipTransport_->isSecure()) { JAMI_WARN("[call:%s] Crypto (SRTP) is negotiated over an insecure signaling transport", getCallId().c_str()); } // reset readyToRecord_ = false; for (auto iter = rtpStreams_.begin(); iter != rtpStreams_.end(); iter++) { if (not iter->mediaAttribute_) { throw std::runtime_error("Missing media attribute"); } // Not restarting media loop on hold as it's a huge waste of CPU ressources // because of the audio loop if (getState() != CallState::HOLD) { if (isIceRunning()) { iter->rtpSession_->start(std::move(iter->rtpSocket_), std::move(iter->rtcpSocket_)); } else { iter->rtpSession_->start(nullptr, nullptr); } } } // Media is restarted, we can process the last holding request. isWaitingForIceAndMedia_ = false; if (remainingRequest_ != Request::NoRequest) { bool result = true; switch (remainingRequest_) { case Request::HoldingOn: result = hold(); if (holdCb_) { holdCb_(result); holdCb_ = nullptr; } break; case Request::HoldingOff: result = unhold(); if (offHoldCb_) { offHoldCb_(result); offHoldCb_ = nullptr; } break; case Request::SwitchInput: SIPSessionReinvite(); break; default: break; } remainingRequest_ = Request::NoRequest; } mediaRestartRequired_ = false; #ifdef ENABLE_PLUGIN // Create AVStreams associated with the call createCallAVStreams(); #endif } void SIPCall::restartMediaSender() { JAMI_DBG("[call:%s] Restarting TX media streams", getCallId().c_str()); for (const auto& rtpSession : getRtpSessionList()) rtpSession->restartSender(); } void SIPCall::stopAllMedia() { JAMI_DBG("[call:%s] Stopping all media", getCallId().c_str()); #ifdef ENABLE_VIDEO { std::lock_guard lk(sinksMtx_); for (auto it = callSinksMap_.begin(); it != callSinksMap_.end();) { for (const auto& videoRtp : getRtpSessionList(MediaType::MEDIA_VIDEO)) { auto& videoReceive = std::static_pointer_cast<video::VideoRtpSession>(videoRtp) ->getVideoReceive(); if (videoReceive) { auto& sink = videoReceive->getSink(); sink->detach(it->second.get()); } } it->second->stop(); it = callSinksMap_.erase(it); } } #endif for (const auto& rtpSession : getRtpSessionList()) rtpSession->stop(); #ifdef ENABLE_PLUGIN { clearCallAVStreams(); std::lock_guard lk(avStreamsMtx_); Manager::instance().getJamiPluginManager().getCallServicesManager().clearAVSubject( getCallId()); } #endif } void SIPCall::updateRemoteMedia() { JAMI_DBG("[call:%s] Updating remote media", getCallId().c_str()); auto remoteMediaList = Sdp::getMediaAttributeListFromSdp(sdp_->getActiveRemoteSdpSession()); if (remoteMediaList.size() != rtpStreams_.size()) { JAMI_ERR("[call:%s] Media size mismatch!", getCallId().c_str()); return; } for (size_t idx = 0; idx < remoteMediaList.size(); idx++) { auto& rtpStream = rtpStreams_[idx]; auto const& remoteMedia = rtpStream.remoteMediaAttribute_ = std::make_shared<MediaAttribute>( remoteMediaList[idx]); if (remoteMedia->type_ == MediaType::MEDIA_VIDEO) { rtpStream.rtpSession_->setMuted(remoteMedia->muted_, RtpSession::Direction::RECV); JAMI_DEBUG("[call:{:s}] Remote media @ {:d}: {:s}", getCallId(), idx, remoteMedia->toString()); // Request a key-frame if we are un-muting the video if (not remoteMedia->muted_) requestKeyframe(findRtpStreamIndex(remoteMedia->label_)); } } } void SIPCall::muteMedia(const std::string& mediaType, bool mute) { auto type = MediaAttribute::stringToMediaType(mediaType); if (type == MediaType::MEDIA_AUDIO) { JAMI_WARN("[call:%s] %s all audio media", getCallId().c_str(), mute ? "muting " : "un-muting "); } else if (type == MediaType::MEDIA_VIDEO) { JAMI_WARN("[call:%s] %s all video media", getCallId().c_str(), mute ? "muting" : "un-muting"); } else { JAMI_ERR("[call:%s] Invalid media type %s", getCallId().c_str(), mediaType.c_str()); assert(false); } // Get the current media attributes. auto mediaList = getMediaAttributeList(); // Mute/Un-mute all medias with matching type. for (auto& mediaAttr : mediaList) { if (mediaAttr.type_ == type) { mediaAttr.muted_ = mute; } } // Apply requestMediaChange(MediaAttribute::mediaAttributesToMediaMaps(mediaList)); } void SIPCall::updateMediaStream(const MediaAttribute& newMediaAttr, size_t streamIdx) { assert(streamIdx < rtpStreams_.size()); auto const& rtpStream = rtpStreams_[streamIdx]; assert(rtpStream.rtpSession_); auto const& mediaAttr = rtpStream.mediaAttribute_; assert(mediaAttr); bool notifyMute = false; if (newMediaAttr.muted_ == mediaAttr->muted_) { // Nothing to do. Already in the desired state. JAMI_DEBUG("[call:{}] [{}] already {}", getCallId(), mediaAttr->label_, mediaAttr->muted_ ? "muted " : "un-muted "); } else { // Update mediaAttr->muted_ = newMediaAttr.muted_; notifyMute = true; JAMI_DEBUG("[call:{}] {} [{}]", getCallId(), mediaAttr->muted_ ? "muting" : "un-muting", mediaAttr->label_); } // Only update source and type if actually set. if (not newMediaAttr.sourceUri_.empty()) mediaAttr->sourceUri_ = newMediaAttr.sourceUri_; if (notifyMute and mediaAttr->type_ == MediaType::MEDIA_AUDIO) { rtpStream.rtpSession_->setMediaSource(mediaAttr->sourceUri_); rtpStream.rtpSession_->setMuted(mediaAttr->muted_); sendMuteState(mediaAttr->muted_); if (not isSubcall()) emitSignal<libjami::CallSignal::AudioMuted>(getCallId(), mediaAttr->muted_); return; } #ifdef ENABLE_VIDEO if (notifyMute and mediaAttr->type_ == MediaType::MEDIA_VIDEO) { rtpStream.rtpSession_->setMediaSource(mediaAttr->sourceUri_); rtpStream.rtpSession_->setMuted(mediaAttr->muted_); if (not isSubcall()) emitSignal<libjami::CallSignal::VideoMuted>(getCallId(), mediaAttr->muted_); } #endif } bool SIPCall::updateAllMediaStreams(const std::vector<MediaAttribute>& mediaAttrList, bool isRemote) { JAMI_DBG("[call:%s] New local media", getCallId().c_str()); if (mediaAttrList.size() > PJ_ICE_MAX_COMP / 2) { JAMI_DEBUG("[call:{:s}] Too many medias, limit it ({:d} vs {:d})", getCallId().c_str(), mediaAttrList.size(), PJ_ICE_MAX_COMP); return false; } unsigned idx = 0; for (auto const& newMediaAttr : mediaAttrList) { JAMI_DBG("[call:%s] Media @%u: %s", getCallId().c_str(), idx++, newMediaAttr.toString(true).c_str()); } JAMI_DBG("[call:%s] Updating local media streams", getCallId().c_str()); for (auto const& newAttr : mediaAttrList) { auto streamIdx = findRtpStreamIndex(newAttr.label_); if (streamIdx < 0) { // Media does not exist, add a new one. addMediaStream(newAttr); auto& stream = rtpStreams_.back(); // If the remote asks for a new stream, our side sends nothing stream.mediaAttribute_->muted_ = isRemote ? true : stream.mediaAttribute_->muted_; createRtpSession(stream); JAMI_DBG("[call:%s] Added a new media stream [%s] @ index %i", getCallId().c_str(), stream.mediaAttribute_->label_.c_str(), streamIdx); } else { updateMediaStream(newAttr, streamIdx); } } if (mediaAttrList.size() < rtpStreams_.size()) { #ifdef ENABLE_VIDEO // If new medias list got more medias than current size, we can remove old medias from conference for (auto i = mediaAttrList.size(); i < rtpStreams_.size(); ++i) { auto& stream = rtpStreams_[i]; if (stream.rtpSession_->getMediaType() == MediaType::MEDIA_VIDEO) std::static_pointer_cast<video::VideoRtpSession>(stream.rtpSession_) ->exitConference(); } #endif rtpStreams_.resize(mediaAttrList.size()); } return true; } bool SIPCall::isReinviteRequired(const std::vector<MediaAttribute>& mediaAttrList) { if (mediaAttrList.size() != rtpStreams_.size()) return true; for (auto const& newAttr : mediaAttrList) { auto streamIdx = findRtpStreamIndex(newAttr.label_); if (streamIdx < 0) { // Always needs a re-invite when a new media is added. return true; } // Changing the source needs a re-invite if (newAttr.sourceUri_ != rtpStreams_[streamIdx].mediaAttribute_->sourceUri_) { return true; } #ifdef ENABLE_VIDEO if (newAttr.type_ == MediaType::MEDIA_VIDEO) { // For now, only video mute triggers a re-invite. // Might be done for audio as well if required. if (newAttr.muted_ != rtpStreams_[streamIdx].mediaAttribute_->muted_) { return true; } } #endif } return false; } bool SIPCall::isNewIceMediaRequired(const std::vector<MediaAttribute>& mediaAttrList) { // Always needs a new ICE media if the peer does not support // re-invite without ICE renegotiation if (not peerSupportReuseIceInReinv_) return true; // Always needs a new ICE media when the number of media changes. if (mediaAttrList.size() != rtpStreams_.size()) return true; for (auto const& newAttr : mediaAttrList) { auto streamIdx = findRtpStreamIndex(newAttr.label_); if (streamIdx < 0) { // Always needs a new ICE media when a media is added or replaced. return true; } auto const& currAttr = rtpStreams_[streamIdx].mediaAttribute_; if (newAttr.sourceUri_ != currAttr->sourceUri_) { // For now, media will be restarted if the source changes. // TODO. This should not be needed if the decoder/receiver // correctly handles dynamic media properties changes. return true; } } return false; } bool SIPCall::requestMediaChange(const std::vector<libjami::MediaMap>& mediaList) { std::lock_guard lk {callMutex_}; auto mediaAttrList = MediaAttribute::buildMediaAttributesList(mediaList, isSrtpEnabled()); bool hasFileSharing {false}; for (const auto& media : mediaAttrList) { if (!media.enabled_ || media.sourceUri_.empty()) continue; // Supported MRL schemes static const std::string sep = libjami::Media::VideoProtocolPrefix::SEPARATOR; const auto pos = media.sourceUri_.find(sep); if (pos == std::string::npos) continue; const auto prefix = media.sourceUri_.substr(0, pos); if ((pos + sep.size()) >= media.sourceUri_.size()) continue; if (prefix == libjami::Media::VideoProtocolPrefix::FILE) { hasFileSharing = true; mediaPlayerId_ = media.sourceUri_; #ifdef ENABLE_VIDEO createMediaPlayer(mediaPlayerId_); #endif } } if (!hasFileSharing) { #ifdef ENABLE_VIDEO closeMediaPlayer(mediaPlayerId_); #endif mediaPlayerId_ = ""; } // Disable video if disabled in the account. auto account = getSIPAccount(); if (not account) { JAMI_ERROR("[call:{}] No account detected", getCallId()); return false; } if (not account->isVideoEnabled()) { for (auto& mediaAttr : mediaAttrList) { if (mediaAttr.type_ == MediaType::MEDIA_VIDEO) { // This an API misuse. The new medialist should not contain video // if it was disabled in the account settings. JAMI_ERROR("[call:{}] New media has video, but it's disabled in the account. " "Ignoring the change request!", getCallId()); return false; } } } // If the peer does not support multi-stream and the size of the new // media list is different from the current media list, the media // change request will be ignored. if (not peerSupportMultiStream_ and rtpStreams_.size() != mediaAttrList.size()) { JAMI_WARNING("[call:{}] Peer does not support multi-stream. Media change request ignored", getCallId()); return false; } // If the peer does not support multi-audio-stream and the new // media list has more than one audio. Ignore the one that comes from a file. if (not peerSupportMultiAudioStream_ and rtpStreams_.size() != mediaAttrList.size() and hasFileSharing) { JAMI_WARNING("[call:{}] Peer does not support multi-audio-stream. New Audio will be ignored", getCallId()); for (auto it = mediaAttrList.begin(); it != mediaAttrList.end();) { if (it->type_ == MediaType::MEDIA_AUDIO and !it->sourceUri_.empty() and mediaPlayerId_ == it->sourceUri_) { it = mediaAttrList.erase(it); continue; } ++it; } } // If peer doesn't support multiple ice, keep only the last audio/video // This keep the old behaviour (if sharing both camera + sharing a file, will keep the shared file) if (!peerSupportMultiIce_) { if (mediaList.size() > 2) JAMI_WARNING("[call:{}] Peer does not support more than 2 ICE medias. Media change " "request modified", getCallId()); MediaAttribute audioAttr; MediaAttribute videoAttr; auto hasVideo = false, hasAudio = false; for (auto it = mediaAttrList.rbegin(); it != mediaAttrList.rend(); ++it) { if (it->type_ == MediaType::MEDIA_VIDEO && !hasVideo) { videoAttr = *it; videoAttr.label_ = sip_utils::DEFAULT_VIDEO_STREAMID; hasVideo = true; } else if (it->type_ == MediaType::MEDIA_AUDIO && !hasAudio) { audioAttr = *it; audioAttr.label_ = sip_utils::DEFAULT_AUDIO_STREAMID; hasAudio = true; } if (hasVideo && hasAudio) break; } mediaAttrList.clear(); // Note: use the order VIDEO/AUDIO to avoid reinvite. mediaAttrList.emplace_back(audioAttr); if (hasVideo) mediaAttrList.emplace_back(videoAttr); } if (mediaAttrList.empty()) { JAMI_ERROR("[call:{}] Invalid media change request: new media list is empty", getCallId()); return false; } JAMI_DEBUG("[call:{}] Requesting media change. List of new media:", getCallId()); unsigned idx = 0; for (auto const& newMediaAttr : mediaAttrList) { JAMI_DEBUG("[call:{}] Media @{:d}: {}", getCallId(), idx++, newMediaAttr.toString(true)); } auto needReinvite = isReinviteRequired(mediaAttrList); auto needNewIce = isNewIceMediaRequired(mediaAttrList); if (!updateAllMediaStreams(mediaAttrList, false)) return false; if (needReinvite) { JAMI_DEBUG("[call:{}] Media change requires a new negotiation (re-invite)", getCallId()); requestReinvite(mediaAttrList, needNewIce); } else { JAMI_DEBUG("[call:{}] Media change DOES NOT require a new negotiation (re-invite)", getCallId()); reportMediaNegotiationStatus(); } return true; } std::vector<std::map<std::string, std::string>> SIPCall::currentMediaList() const { return MediaAttribute::mediaAttributesToMediaMaps(getMediaAttributeList()); } std::vector<MediaAttribute> SIPCall::getMediaAttributeList() const { std::lock_guard lk {callMutex_}; std::vector<MediaAttribute> mediaList; mediaList.reserve(rtpStreams_.size()); for (auto const& stream : rtpStreams_) mediaList.emplace_back(*stream.mediaAttribute_); return mediaList; } std::map<std::string, bool> SIPCall::getAudioStreams() const { std::map<std::string, bool> audioMedias {}; auto medias = getMediaAttributeList(); for (const auto& media : medias) { if (media.type_ == MEDIA_AUDIO) { auto label = fmt::format("{}_{}", getCallId(), media.label_); audioMedias.emplace(label, media.muted_); } } return audioMedias; } void SIPCall::onMediaNegotiationComplete() { runOnMainThread([w = weak()] { if (auto this_ = w.lock()) { std::lock_guard lk {this_->callMutex_}; JAMI_DBG("[call:%s] Media negotiation complete", this_->getCallId().c_str()); // If the call has already ended, we don't need to start the media. if (not this_->inviteSession_ or this_->inviteSession_->state == PJSIP_INV_STATE_DISCONNECTED or not this_->sdp_) { return; } // This method is called to report media negotiation (SDP) for initial // invite or subsequent invites (re-invite). // If ICE is negotiated, the media update will be handled in the // ICE callback, otherwise, it will be handled here. // Note that ICE can be negotiated in the first invite and not negotiated // in the re-invite. In this case, the media transport is unchanged (reused). if (this_->isIceEnabled() and this_->remoteHasValidIceAttributes()) { if (not this_->isSubcall()) { // Start ICE checks. Media will be started once ICE checks complete. this_->startIceMedia(); } } else { // Update the negotiated media. if (this_->mediaRestartRequired_) { this_->setupNegotiatedMedia(); // No ICE, start media now. JAMI_WARN("[call:%s] ICE media disabled, using default media ports", this_->getCallId().c_str()); // Start the media. this_->stopAllMedia(); this_->startAllMedia(); } this_->updateRemoteMedia(); this_->reportMediaNegotiationStatus(); } } }); } void SIPCall::reportMediaNegotiationStatus() { // Notify using the parent Id if it's a subcall. auto callId = isSubcall() ? parent_->getCallId() : getCallId(); emitSignal<libjami::CallSignal::MediaNegotiationStatus>( callId, libjami::Media::MediaNegotiationStatusEvents::NEGOTIATION_SUCCESS, currentMediaList()); auto previousState = isAudioOnly_; auto newState = !hasVideo(); if (previousState != newState && Call::isRecording()) { deinitRecorder(); toggleRecording(); pendingRecord_ = true; } isAudioOnly_ = newState; if (pendingRecord_ && readyToRecord_) { toggleRecording(); } } void SIPCall::startIceMedia() { JAMI_DBG("[call:%s] Starting ICE", getCallId().c_str()); auto iceMedia = getIceMedia(); if (not iceMedia or iceMedia->isFailed()) { JAMI_ERR("[call:%s] Media ICE init failed", getCallId().c_str()); onFailure(EIO); return; } if (iceMedia->isStarted()) { // NOTE: for incoming calls, the ice is already there and running if (iceMedia->isRunning()) onIceNegoSucceed(); return; } if (not iceMedia->isInitialized()) { // In this case, onInitDone will occurs after the startIceMedia waitForIceInit_ = true; return; } // Start transport on SDP data and wait for negotiation if (!sdp_) return; auto rem_ice_attrs = sdp_->getIceAttributes(); if (rem_ice_attrs.ufrag.empty() or rem_ice_attrs.pwd.empty()) { JAMI_ERR("[call:%s] Missing remote media ICE attributes", getCallId().c_str()); onFailure(EIO); return; } if (not iceMedia->startIce(rem_ice_attrs, getAllRemoteCandidates(*iceMedia))) { JAMI_ERR("[call:%s] ICE media failed to start", getCallId().c_str()); onFailure(EIO); } } void SIPCall::onIceNegoSucceed() { std::lock_guard lk {callMutex_}; JAMI_DBG("[call:%s] ICE negotiation succeeded", getCallId().c_str()); // Check if the call is already ended, so we don't need to restart medias // This is typically the case in a multi-device context where one device // can stop a call. So do not start medias if (not inviteSession_ or inviteSession_->state == PJSIP_INV_STATE_DISCONNECTED or not sdp_) { JAMI_ERR("[call:%s] ICE negotiation succeeded, but call is in invalid state", getCallId().c_str()); return; } // Update the negotiated media. setupNegotiatedMedia(); // If this callback is for a re-invite session then update // the ICE media transport. if (isIceEnabled()) switchToIceReinviteIfNeeded(); for (unsigned int idx = 0, compId = 1; idx < rtpStreams_.size(); idx++, compId += 2) { // Create sockets for RTP and RTCP, and start the session. auto& rtpStream = rtpStreams_[idx]; rtpStream.rtpSocket_ = newIceSocket(compId); if (not rtcpMuxEnabled_) { rtpStream.rtcpSocket_ = newIceSocket(compId + 1); } } // Start/Restart the media using the new transport stopAllMedia(); startAllMedia(); updateRemoteMedia(); reportMediaNegotiationStatus(); } bool SIPCall::checkMediaChangeRequest(const std::vector<libjami::MediaMap>& remoteMediaList) { // The current media is considered to have changed if one of the // following condtions is true: // // - the number of media changed // - the type of one of the media changed (unlikely) // - one of the media was enabled/disabled JAMI_DBG("[call:%s] Received a media change request", getCallId().c_str()); auto remoteMediaAttrList = MediaAttribute::buildMediaAttributesList(remoteMediaList, isSrtpEnabled()); if (remoteMediaAttrList.size() != rtpStreams_.size()) return true; for (size_t i = 0; i < rtpStreams_.size(); i++) { if (remoteMediaAttrList[i].type_ != rtpStreams_[i].mediaAttribute_->type_) return true; if (remoteMediaAttrList[i].enabled_ != rtpStreams_[i].mediaAttribute_->enabled_) return true; } return false; } void SIPCall::handleMediaChangeRequest(const std::vector<libjami::MediaMap>& remoteMediaList) { JAMI_DBG("[call:%s] Handling media change request", getCallId().c_str()); auto account = getAccount().lock(); if (not account) { JAMI_ERR("No account detected"); return; } // If the offered media does not differ from the current local media, the // request is answered using the current local media. if (not checkMediaChangeRequest(remoteMediaList)) { answerMediaChangeRequest( MediaAttribute::mediaAttributesToMediaMaps(getMediaAttributeList())); return; } if (account->isAutoAnswerEnabled()) { // NOTE: // Since the auto-answer is enabled in the account, newly // added media are accepted too. // This also means that if original call was an audio-only call, // the local camera will be enabled, unless the video is disabled // in the account settings. std::vector<libjami::MediaMap> newMediaList; newMediaList.reserve(remoteMediaList.size()); for (auto const& stream : rtpStreams_) { newMediaList.emplace_back(MediaAttribute::toMediaMap(*stream.mediaAttribute_)); } assert(remoteMediaList.size() > 0); if (remoteMediaList.size() > newMediaList.size()) { for (auto idx = newMediaList.size(); idx < remoteMediaList.size(); idx++) { newMediaList.emplace_back(remoteMediaList[idx]); } } answerMediaChangeRequest(newMediaList, true); return; } // Report the media change request. emitSignal<libjami::CallSignal::MediaChangeRequested>(getAccountId(), getCallId(), remoteMediaList); } pj_status_t SIPCall::onReceiveReinvite(const pjmedia_sdp_session* offer, pjsip_rx_data* rdata) { JAMI_DBG("[call:%s] Received a re-invite", getCallId().c_str()); pj_status_t res = PJ_SUCCESS; if (not sdp_) { JAMI_ERR("SDP session is invalid"); return res; } sdp_->clearIce(); sdp_->setActiveRemoteSdpSession(nullptr); sdp_->setActiveLocalSdpSession(nullptr); auto acc = getSIPAccount(); if (not acc) { JAMI_ERR("No account detected"); return res; } Sdp::printSession(offer, "Remote session (media change request)", SdpDirection::OFFER); sdp_->setReceivedOffer(offer); // Note: For multistream, here we must ignore disabled remote medias, because // we will answer from our medias and remote enabled medias. // Example: if remote disables its camera and share its screen, the offer will // have an active and a disabled media (with port = 0). // In this case, if we have only one video, we can just negotiate 1 video instead of 2 // with 1 disabled. // cf. pjmedia_sdp_neg_modify_local_offer2 for more details. auto const& mediaAttrList = Sdp::getMediaAttributeListFromSdp(offer, true); if (mediaAttrList.empty()) { JAMI_WARN("[call:%s] Media list is empty, ignoring", getCallId().c_str()); return res; } if (upnp_) { openPortsUPnP(); } pjsip_tx_data* tdata = nullptr; if (pjsip_inv_initial_answer(inviteSession_.get(), rdata, PJSIP_SC_TRYING, NULL, NULL, &tdata) != PJ_SUCCESS) { JAMI_ERR("[call:%s] Unable to create answer TRYING", getCallId().c_str()); return res; } dht::ThreadPool::io().run([callWkPtr = weak(), mediaAttrList] { if (auto call = callWkPtr.lock()) { // Report the change request. auto const& remoteMediaList = MediaAttribute::mediaAttributesToMediaMaps(mediaAttrList); if (auto conf = call->getConference()) { conf->handleMediaChangeRequest(call, remoteMediaList); } else { call->handleMediaChangeRequest(remoteMediaList); } } }); return res; } void SIPCall::onReceiveOfferIn200OK(const pjmedia_sdp_session* offer) { if (not rtpStreams_.empty()) { JAMI_ERR("[call:%s] Unexpected offer in '200 OK' answer", getCallId().c_str()); return; } auto acc = getSIPAccount(); if (not acc) { JAMI_ERR("No account detected"); return; } if (not sdp_) { JAMI_ERR("Invalid SDP session"); return; } JAMI_DBG("[call:%s] Received an offer in '200 OK' answer", getCallId().c_str()); auto mediaList = Sdp::getMediaAttributeListFromSdp(offer); // If this method is called, it means we are expecting an offer // in the 200OK answer. if (mediaList.empty()) { JAMI_WARN("[call:%s] Remote media list is empty, ignoring", getCallId().c_str()); return; } Sdp::printSession(offer, "Remote session (offer in 200 OK answer)", SdpDirection::OFFER); sdp_->clearIce(); sdp_->setActiveRemoteSdpSession(nullptr); sdp_->setActiveLocalSdpSession(nullptr); sdp_->setReceivedOffer(offer); // If we send an empty offer, video will be accepted only if locally // enabled by the user. for (auto& mediaAttr : mediaList) { if (mediaAttr.type_ == MediaType::MEDIA_VIDEO and not acc->isVideoEnabled()) { mediaAttr.enabled_ = false; } } initMediaStreams(mediaList); sdp_->processIncomingOffer(mediaList); if (upnp_) { openPortsUPnP(); } if (isIceEnabled() and remoteHasValidIceAttributes()) { setupIceResponse(); } sdp_->startNegotiation(); if (pjsip_inv_set_sdp_answer(inviteSession_.get(), sdp_->getLocalSdpSession()) != PJ_SUCCESS) { JAMI_ERR("[call:%s] Unable to start media negotiation for a re-invite request", getCallId().c_str()); } } void SIPCall::openPortsUPnP() { if (not sdp_) { JAMI_ERR("[call:%s] Current SDP instance is invalid", getCallId().c_str()); return; } /** * Try to open the desired ports with UPnP, * if they are used, use the alternative port and update the SDP session with the newly * chosen port(s) * * TODO: * No need to request mappings for specfic port numbers. Set the port to '0' to * request the first available port (faster and more likely to succeed). */ JAMI_DBG("[call:%s] Opening ports via UPNP for SDP session", getCallId().c_str()); // RTP port. upnp_->reserveMapping(sdp_->getLocalAudioPort(), dhtnet::upnp::PortType::UDP); // RTCP port. upnp_->reserveMapping(sdp_->getLocalAudioControlPort(), dhtnet::upnp::PortType::UDP); #ifdef ENABLE_VIDEO // RTP port. upnp_->reserveMapping(sdp_->getLocalVideoPort(), dhtnet::upnp::PortType::UDP); // RTCP port. upnp_->reserveMapping(sdp_->getLocalVideoControlPort(), dhtnet::upnp::PortType::UDP); #endif } std::map<std::string, std::string> SIPCall::getDetails() const { auto acc = getSIPAccount(); if (!acc) { JAMI_ERR("No account detected"); return {}; } auto details = Call::getDetails(); details.emplace(libjami::Call::Details::PEER_HOLDING, peerHolding_ ? TRUE_STR : FALSE_STR); for (auto const& stream : rtpStreams_) { if (stream.mediaAttribute_->type_ == MediaType::MEDIA_VIDEO) { details.emplace(libjami::Call::Details::VIDEO_SOURCE, stream.mediaAttribute_->sourceUri_); #ifdef ENABLE_VIDEO if (auto const& rtpSession = stream.rtpSession_) { if (auto codec = rtpSession->getCodec()) { details.emplace(libjami::Call::Details::VIDEO_CODEC, codec->name); details.emplace(libjami::Call::Details::VIDEO_MIN_BITRATE, std::to_string(codec->minBitrate)); details.emplace(libjami::Call::Details::VIDEO_MAX_BITRATE, std::to_string(codec->maxBitrate)); if (const auto& curvideoRtpSession = std::static_pointer_cast<video::VideoRtpSession>(rtpSession)) { details.emplace(libjami::Call::Details::VIDEO_BITRATE, std::to_string(curvideoRtpSession->getVideoBitrateInfo() .videoBitrateCurrent)); } } else details.emplace(libjami::Call::Details::VIDEO_CODEC, ""); } #endif } else if (stream.mediaAttribute_->type_ == MediaType::MEDIA_AUDIO) { if (auto const& rtpSession = stream.rtpSession_) { if (auto codec = rtpSession->getCodec()) { details.emplace(libjami::Call::Details::AUDIO_CODEC, codec->name); details.emplace(libjami::Call::Details::AUDIO_SAMPLE_RATE, codec->getCodecSpecifications() [libjami::Account::ConfProperties::CodecInfo::SAMPLE_RATE]); } else { details.emplace(libjami::Call::Details::AUDIO_CODEC, ""); details.emplace(libjami::Call::Details::AUDIO_SAMPLE_RATE, ""); } } } } #if HAVE_RINGNS if (not peerRegisteredName_.empty()) details.emplace(libjami::Call::Details::REGISTERED_NAME, peerRegisteredName_); #endif #ifdef ENABLE_CLIENT_CERT std::lock_guard lk {callMutex_}; if (transport_ and transport_->isSecure()) { const auto& tlsInfos = transport_->getTlsInfos(); if (tlsInfos.cipher != PJ_TLS_UNKNOWN_CIPHER) { const auto& cipher = pj_ssl_cipher_name(tlsInfos.cipher); details.emplace(libjami::TlsTransport::TLS_CIPHER, cipher ? cipher : ""); } else { details.emplace(libjami::TlsTransport::TLS_CIPHER, ""); } if (tlsInfos.peerCert) { details.emplace(libjami::TlsTransport::TLS_PEER_CERT, tlsInfos.peerCert->toString()); auto ca = tlsInfos.peerCert->issuer; unsigned n = 0; while (ca) { std::ostringstream name_str; name_str << libjami::TlsTransport::TLS_PEER_CA_ << n++; details.emplace(name_str.str(), ca->toString()); ca = ca->issuer; } details.emplace(libjami::TlsTransport::TLS_PEER_CA_NUM, std::to_string(n)); } else { details.emplace(libjami::TlsTransport::TLS_PEER_CERT, ""); details.emplace(libjami::TlsTransport::TLS_PEER_CA_NUM, ""); } } #endif if (auto transport = getIceMedia()) { if (transport && transport->isRunning()) details.emplace(libjami::Call::Details::SOCKETS, transport->link().c_str()); } return details; } void SIPCall::enterConference(std::shared_ptr<Conference> conference) { JAMI_DEBUG("[call:{}] Entering conference [{}]", getCallId(), conference->getConfId()); conf_ = conference; // Unbind audio. It will be rebinded in the conference if needed auto const hasAudio = !getRtpSessionList(MediaType::MEDIA_AUDIO).empty(); if (hasAudio) { auto& rbPool = Manager::instance().getRingBufferPool(); auto medias = getAudioStreams(); for (const auto& media : medias) { rbPool.unbindRingbuffers(media.first, RingBufferPool::DEFAULT_ID); } rbPool.flush(RingBufferPool::DEFAULT_ID); } #ifdef ENABLE_VIDEO if (conference->isVideoEnabled()) for (const auto& videoRtp : getRtpSessionList(MediaType::MEDIA_VIDEO)) std::static_pointer_cast<video::VideoRtpSession>(videoRtp)->enterConference(*conference); #endif #ifdef ENABLE_PLUGIN clearCallAVStreams(); #endif } void SIPCall::exitConference() { std::lock_guard lk {callMutex_}; JAMI_DBG("[call:%s] Leaving conference", getCallId().c_str()); auto const hasAudio = !getRtpSessionList(MediaType::MEDIA_AUDIO).empty(); if (hasAudio) { auto& rbPool = Manager::instance().getRingBufferPool(); auto medias = getAudioStreams(); for (const auto& media : medias) { if (!media.second) { rbPool.bindRingbuffers(media.first, RingBufferPool::DEFAULT_ID); } } rbPool.flush(RingBufferPool::DEFAULT_ID); } #ifdef ENABLE_VIDEO for (const auto& videoRtp : getRtpSessionList(MediaType::MEDIA_VIDEO)) std::static_pointer_cast<video::VideoRtpSession>(videoRtp)->exitConference(); #endif #ifdef ENABLE_PLUGIN createCallAVStreams(); #endif conf_.reset(); } void SIPCall::setActiveMediaStream(const std::string& accountUri, const std::string& deviceId, const std::string& streamId, const bool& state) { auto remoteStreamId = streamId; #ifdef ENABLE_VIDEO { std::lock_guard lk(sinksMtx_); const auto& localIt = local2RemoteSinks_.find(streamId); if (localIt != local2RemoteSinks_.end()) { remoteStreamId = localIt->second; } } #endif if (Call::conferenceProtocolVersion() == 1) { Json::Value sinkVal; sinkVal["active"] = state; Json::Value mediasObj; mediasObj[remoteStreamId] = sinkVal; Json::Value deviceVal; deviceVal["medias"] = mediasObj; Json::Value deviceObj; deviceObj[deviceId] = deviceVal; Json::Value accountVal; deviceVal["devices"] = deviceObj; Json::Value root; root[accountUri] = deviceVal; root["version"] = 1; Call::sendConfOrder(root); } else if (Call::conferenceProtocolVersion() == 0) { Json::Value root; root["activeParticipant"] = accountUri; Call::sendConfOrder(root); } } #ifdef ENABLE_VIDEO void SIPCall::setRotation(int streamIdx, int rotation) { // Retrigger on another thread to avoid to lock pjsip dht::ThreadPool::io().run([w = weak(), streamIdx, rotation] { if (auto shared = w.lock()) { std::lock_guard lk {shared->callMutex_}; shared->rotation_ = rotation; if (streamIdx == -1) { for (const auto& videoRtp : shared->getRtpSessionList(MediaType::MEDIA_VIDEO)) std::static_pointer_cast<video::VideoRtpSession>(videoRtp)->setRotation(rotation); } else if (streamIdx > -1 && streamIdx < static_cast<int>(shared->rtpStreams_.size())) { // Apply request for wanted stream auto& stream = shared->rtpStreams_[streamIdx]; if (stream.rtpSession_ && stream.rtpSession_->getMediaType() == MediaType::MEDIA_VIDEO) std::static_pointer_cast<video::VideoRtpSession>(stream.rtpSession_) ->setRotation(rotation); } } }); } void SIPCall::createSinks(ConfInfo& infos) { std::lock_guard lk(callMutex_); std::lock_guard lkS(sinksMtx_); if (!hasVideo()) return; for (auto& participant : infos) { if (string_remove_suffix(participant.uri, '@') == account_.lock()->getUsername() && participant.device == std::dynamic_pointer_cast<JamiAccount>(account_.lock())->currentDeviceId()) { for (auto iter = rtpStreams_.begin(); iter != rtpStreams_.end(); iter++) { if (!iter->mediaAttribute_ || iter->mediaAttribute_->type_ == MediaType::MEDIA_AUDIO) { continue; } auto localVideo = std::static_pointer_cast<video::VideoRtpSession>(iter->rtpSession_) ->getVideoLocal().get(); auto size = std::make_pair(10, 10); if (localVideo) { size = std::make_pair(localVideo->getWidth(), localVideo->getHeight()); } const auto& mediaAttribute = iter->mediaAttribute_; if (participant.sinkId.find(mediaAttribute->label_) != std::string::npos) { local2RemoteSinks_[mediaAttribute->sourceUri_] = participant.sinkId; participant.sinkId = mediaAttribute->sourceUri_; participant.videoMuted = mediaAttribute->muted_; participant.w = size.first; participant.h = size.second; participant.x = 0; participant.y = 0; } } } } std::vector<std::shared_ptr<video::VideoFrameActiveWriter>> sinks; for (const auto& videoRtp : getRtpSessionList(MediaType::MEDIA_VIDEO)) { auto& videoReceive = std::static_pointer_cast<video::VideoRtpSession>(videoRtp) ->getVideoReceive(); if (!videoReceive) continue; sinks.emplace_back( std::static_pointer_cast<video::VideoFrameActiveWriter>(videoReceive->getSink())); } auto conf = conf_.lock(); const auto& id = conf ? conf->getConfId() : getCallId(); Manager::instance().createSinkClients(id, infos, sinks, callSinksMap_); } #endif std::vector<std::shared_ptr<RtpSession>> SIPCall::getRtpSessionList(MediaType type) const { std::vector<std::shared_ptr<RtpSession>> rtpList; rtpList.reserve(rtpStreams_.size()); for (auto const& stream : rtpStreams_) { if (type == MediaType::MEDIA_ALL || stream.rtpSession_->getMediaType() == type) rtpList.emplace_back(stream.rtpSession_); } return rtpList; } void SIPCall::monitor() const { if (isSubcall()) return; auto acc = getSIPAccount(); if (!acc) { JAMI_ERR("No account detected"); return; } JAMI_DBG("- Call %s with %s:", getCallId().c_str(), getPeerNumber().c_str()); JAMI_DBG("\t- Duration: %s", dht::print_duration(getCallDuration()).c_str()); for (const auto& stream : rtpStreams_) JAMI_DBG("\t- Media: %s", stream.mediaAttribute_->toString(true).c_str()); #ifdef ENABLE_VIDEO if (auto codec = getVideoCodec()) JAMI_DBG("\t- Video codec: %s", codec->name.c_str()); #endif if (auto transport = getIceMedia()) { if (transport->isRunning()) JAMI_DBG("\t- Medias: %s", transport->link().c_str()); } } bool SIPCall::toggleRecording() { pendingRecord_ = true; if (not readyToRecord_) return true; // add streams to recorder before starting the record if (not Call::isRecording()) { auto account = getSIPAccount(); if (!account) { JAMI_ERR("No account detected"); return false; } auto title = fmt::format("Conversation at %TIMESTAMP between {} and {}", account->getUserUri(), peerUri_); recorder_->setMetadata(title, ""); // use default description for (const auto& rtpSession : getRtpSessionList()) rtpSession->initRecorder(); } else { updateRecState(false); } pendingRecord_ = false; auto state = Call::toggleRecording(); if (state) updateRecState(state); return state; } void SIPCall::deinitRecorder() { for (const auto& rtpSession : getRtpSessionList()) rtpSession->deinitRecorder(); } void SIPCall::InvSessionDeleter::operator()(pjsip_inv_session* inv) const noexcept { // prevent this from getting accessed in callbacks // JAMI_WARN: this is not thread-safe! if (!inv) return; inv->mod_data[Manager::instance().sipVoIPLink().getModId()] = nullptr; // NOTE: the counter is incremented by sipvoiplink (transaction_request_cb) pjsip_inv_dec_ref(inv); } bool SIPCall::createIceMediaTransport(bool isReinvite) { auto mediaTransport = Manager::instance().getIceTransportFactory()->createTransport(getCallId()); if (mediaTransport) { JAMI_DBG("[call:%s] Successfully created media ICE transport [ice:%p]", getCallId().c_str(), mediaTransport.get()); } else { JAMI_ERR("[call:%s] Failed to create media ICE transport", getCallId().c_str()); return {}; } setIceMedia(mediaTransport, isReinvite); return mediaTransport != nullptr; } bool SIPCall::initIceMediaTransport(bool master, std::optional<dhtnet::IceTransportOptions> options) { auto acc = getSIPAccount(); if (!acc) { JAMI_ERR("No account detected"); return false; } JAMI_DBG("[call:%s] Init media ICE transport", getCallId().c_str()); auto const& iceMedia = getIceMedia(); if (not iceMedia) { JAMI_ERR("[call:%s] Invalid media ICE transport", getCallId().c_str()); return false; } auto iceOptions = options == std::nullopt ? acc->getIceOptions() : *options; auto optOnInitDone = std::move(iceOptions.onInitDone); auto optOnNegoDone = std::move(iceOptions.onNegoDone); iceOptions.onInitDone = [w = weak(), cb = std::move(optOnInitDone)](bool ok) { runOnMainThread([w = std::move(w), cb = std::move(cb), ok] { auto call = w.lock(); if (cb) cb(ok); if (!ok or !call or !call->waitForIceInit_.exchange(false)) return; std::lock_guard lk {call->callMutex_}; auto rem_ice_attrs = call->sdp_->getIceAttributes(); // Init done but no remote_ice_attributes, the ice->start will be triggered later if (rem_ice_attrs.ufrag.empty() or rem_ice_attrs.pwd.empty()) return; call->startIceMedia(); }); }; iceOptions.onNegoDone = [w = weak(), cb = std::move(optOnNegoDone)](bool ok) { runOnMainThread([w = std::move(w), cb = std::move(cb), ok] { if (cb) cb(ok); if (auto call = w.lock()) { // The ICE is related to subcalls, but medias are handled by parent call std::lock_guard lk {call->callMutex_}; call = call->isSubcall() ? std::dynamic_pointer_cast<SIPCall>(call->parent_) : call; if (!ok) { JAMI_ERR("[call:%s] Media ICE negotiation failed", call->getCallId().c_str()); call->onFailure(EIO); return; } call->onIceNegoSucceed(); } }); }; iceOptions.master = master; iceOptions.streamsCount = static_cast<unsigned>(rtpStreams_.size()); // Each RTP stream requires a pair of ICE components (RTP + RTCP). iceOptions.compCountPerStream = ICE_COMP_COUNT_PER_STREAM; iceOptions.qosType.reserve(rtpStreams_.size() * ICE_COMP_COUNT_PER_STREAM); for (const auto& stream : rtpStreams_) { iceOptions.qosType.push_back(stream.mediaAttribute_->type_ == MediaType::MEDIA_AUDIO ? dhtnet::QosType::VOICE : dhtnet::QosType::VIDEO); iceOptions.qosType.push_back(dhtnet::QosType::CONTROL); } // Init ICE. iceMedia->initIceInstance(iceOptions); return true; } std::vector<std::string> SIPCall::getLocalIceCandidates(unsigned compId) const { std::lock_guard lk(transportMtx_); if (not iceMedia_) { JAMI_WARN("[call:%s] No media ICE transport", getCallId().c_str()); return {}; } return iceMedia_->getLocalCandidates(compId); } void SIPCall::resetTransport(std::shared_ptr<dhtnet::IceTransport>&& transport) { // Move the transport to another thread and destroy it there if possible if (transport) { dht::ThreadPool::io().run( [transport = std::move(transport)]() mutable { transport.reset(); }); } } void SIPCall::merge(Call& call) { JAMI_DBG("[call:%s] Merge subcall %s", getCallId().c_str(), call.getCallId().c_str()); // This static cast is safe as this method is private and overload Call::merge auto& subcall = static_cast<SIPCall&>(call); std::lock(callMutex_, subcall.callMutex_); std::lock_guard lk1 {callMutex_, std::adopt_lock}; std::lock_guard lk2 {subcall.callMutex_, std::adopt_lock}; inviteSession_ = std::move(subcall.inviteSession_); if (inviteSession_) inviteSession_->mod_data[Manager::instance().sipVoIPLink().getModId()] = this; setSipTransport(std::move(subcall.sipTransport_), std::move(subcall.contactHeader_)); sdp_ = std::move(subcall.sdp_); peerHolding_ = subcall.peerHolding_; upnp_ = std::move(subcall.upnp_); localAudioPort_ = subcall.localAudioPort_; localVideoPort_ = subcall.localVideoPort_; peerUserAgent_ = subcall.peerUserAgent_; peerSupportMultiStream_ = subcall.peerSupportMultiStream_; peerSupportMultiAudioStream_ = subcall.peerSupportMultiAudioStream_; peerSupportMultiIce_ = subcall.peerSupportMultiIce_; peerAllowedMethods_ = subcall.peerAllowedMethods_; peerSupportReuseIceInReinv_ = subcall.peerSupportReuseIceInReinv_; Call::merge(subcall); if (isIceEnabled()) startIceMedia(); } bool SIPCall::remoteHasValidIceAttributes() const { if (not sdp_) { throw std::runtime_error("Must have a valid SDP Session"); } auto rem_ice_attrs = sdp_->getIceAttributes(); if (rem_ice_attrs.ufrag.empty()) { JAMI_DBG("[call:%s] No ICE username fragment attribute in remote SDP", getCallId().c_str()); return false; } if (rem_ice_attrs.pwd.empty()) { JAMI_DBG("[call:%s] No ICE password attribute in remote SDP", getCallId().c_str()); return false; } return true; } void SIPCall::setIceMedia(std::shared_ptr<dhtnet::IceTransport> ice, bool isReinvite) { std::lock_guard lk(transportMtx_); if (isReinvite) { JAMI_DBG("[call:%s] Setting re-invite ICE session [%p]", getCallId().c_str(), ice.get()); resetTransport(std::move(reinvIceMedia_)); reinvIceMedia_ = std::move(ice); } else { JAMI_DBG("[call:%s] Setting ICE session [%p]", getCallId().c_str(), ice.get()); resetTransport(std::move(iceMedia_)); iceMedia_ = std::move(ice); } } void SIPCall::switchToIceReinviteIfNeeded() { std::lock_guard lk(transportMtx_); if (reinvIceMedia_) { JAMI_DBG("[call:%s] Switching to re-invite ICE session [%p]", getCallId().c_str(), reinvIceMedia_.get()); std::swap(reinvIceMedia_, iceMedia_); } resetTransport(std::move(reinvIceMedia_)); } void SIPCall::setupIceResponse(bool isReinvite) { JAMI_DBG("[call:%s] Setup ICE response", getCallId().c_str()); auto account = getSIPAccount(); if (not account) { JAMI_ERR("No account detected"); } auto opt = account->getIceOptions(); // Try to use the discovered public address. If not available, // fallback on local address. opt.accountPublicAddr = account->getPublishedIpAddress(); if (opt.accountPublicAddr) { opt.accountLocalAddr = dhtnet::ip_utils::getInterfaceAddr(account->getLocalInterface(), opt.accountPublicAddr.getFamily()); } else { // Just set the local address for both, most likely the account is not // registered. opt.accountLocalAddr = dhtnet::ip_utils::getInterfaceAddr(account->getLocalInterface(), AF_INET); opt.accountPublicAddr = opt.accountLocalAddr; } if (not opt.accountLocalAddr) { JAMI_ERR("[call:%s] No local address, unable to initialize ICE", getCallId().c_str()); onFailure(EIO); return; } if (not createIceMediaTransport(isReinvite) or not initIceMediaTransport(false, opt)) { JAMI_ERR("[call:%s] ICE initialization failed", getCallId().c_str()); // Fatal condition // TODO: what's SIP rfc says about that? // (same question in startIceMedia) onFailure(EIO); return; } // Media transport changed, must restart the media. mediaRestartRequired_ = true; // WARNING: This call blocks! (need ice init done) addLocalIceAttributes(); } bool SIPCall::isIceRunning() const { std::lock_guard lk(transportMtx_); return iceMedia_ and iceMedia_->isRunning(); } std::unique_ptr<dhtnet::IceSocket> SIPCall::newIceSocket(unsigned compId) { return std::unique_ptr<dhtnet::IceSocket> {new dhtnet::IceSocket(getIceMedia(), compId)}; } void SIPCall::rtpSetupSuccess() { std::lock_guard lk {setupSuccessMutex_}; readyToRecord_ = true; // We're ready to record whenever a stream is ready auto previousState = isAudioOnly_; auto newState = !hasVideo(); if (previousState != newState && Call::isRecording()) { deinitRecorder(); toggleRecording(); pendingRecord_ = true; } isAudioOnly_ = newState; if (pendingRecord_ && readyToRecord_) toggleRecording(); } void SIPCall::peerRecording(bool state) { auto conference = conf_.lock(); const std::string& id = conference ? conference->getConfId() : getCallId(); if (state) { JAMI_WARN("[call:%s] Peer is recording", getCallId().c_str()); emitSignal<libjami::CallSignal::RemoteRecordingChanged>(id, getPeerNumber(), true); } else { JAMI_WARN("Peer stopped recording"); emitSignal<libjami::CallSignal::RemoteRecordingChanged>(id, getPeerNumber(), false); } peerRecording_ = state; if (auto conf = conf_.lock()) conf->updateRecording(); } void SIPCall::peerMuted(bool muted, int streamIdx) { if (muted) { JAMI_WARN("Peer muted"); } else { JAMI_WARN("Peer unmuted"); } if (streamIdx == -1) { for (const auto& audioRtp : getRtpSessionList(MediaType::MEDIA_AUDIO)) audioRtp->setMuted(muted, RtpSession::Direction::RECV); } else if (streamIdx > -1 && streamIdx < static_cast<int>(rtpStreams_.size())) { auto& stream = rtpStreams_[streamIdx]; if (stream.rtpSession_ && stream.rtpSession_->getMediaType() == MediaType::MEDIA_AUDIO) stream.rtpSession_->setMuted(muted, RtpSession::Direction::RECV); } peerMuted_ = muted; if (auto conf = conf_.lock()) conf->updateMuted(); } void SIPCall::peerVoice(bool voice) { peerVoice_ = voice; if (auto conference = conf_.lock()) { conference->updateVoiceActivity(); } else { // one-to-one call // maybe emit signal with partner voice activity } } } // namespace jami
128,187
C++
.cpp
3,214
31.07654
119
0.602518
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,831
sdp.cpp
savoirfairelinux_jami-daemon/src/sip/sdp.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sdp.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sip/sipaccount.h" #include "sip/sipvoiplink.h" #include "string_utils.h" #include "base64.h" #include "manager.h" #include "logger.h" #include "libav_utils.h" #include "media_codec.h" #include "system_codec_container.h" #include "compiler_intrinsics.h" // for UNUSED #include <opendht/rng.h> #include <algorithm> #include <cassert> namespace jami { using std::string; using std::vector; static constexpr int POOL_INITIAL_SIZE = 16384; static constexpr int POOL_INCREMENT_SIZE = POOL_INITIAL_SIZE; static std::map<MediaDirection, const char*> DIRECTION_STR {{MediaDirection::SENDRECV, "sendrecv"}, {MediaDirection::SENDONLY, "sendonly"}, {MediaDirection::RECVONLY, "recvonly"}, {MediaDirection::INACTIVE, "inactive"}, {MediaDirection::UNKNOWN, "unknown"}}; Sdp::Sdp(const std::string& id) : memPool_(nullptr, [](pj_pool_t* pool) { pj_pool_release(pool); }) , publishedIpAddr_() , publishedIpAddrType_() , telephoneEventPayload_(101) // same as asterisk , sessionName_("Call ID " + id) { memPool_.reset(pj_pool_create(&Manager::instance().sipVoIPLink().getCachingPool()->factory, id.c_str(), POOL_INITIAL_SIZE, POOL_INCREMENT_SIZE, NULL)); if (not memPool_) throw std::runtime_error("pj_pool_create() failed"); } Sdp::~Sdp() { SIPAccount::releasePort(localAudioRtpPort_); #ifdef ENABLE_VIDEO SIPAccount::releasePort(localVideoRtpPort_); #endif } std::shared_ptr<SystemCodecInfo> Sdp::findCodecBySpec(std::string_view codec, const unsigned clockrate) const { // TODO : only manage a list? for (const auto& accountCodec : audio_codec_list_) { auto audioCodecInfo = std::static_pointer_cast<SystemAudioCodecInfo>(accountCodec); if (audioCodecInfo->name == codec and (audioCodecInfo->isPCMG722() ? (clockrate == 8000) : (audioCodecInfo->audioformat.sample_rate == clockrate))) return accountCodec; } for (const auto& accountCodec : video_codec_list_) { if (accountCodec->name == codec) return accountCodec; } return nullptr; } std::shared_ptr<SystemCodecInfo> Sdp::findCodecByPayload(const unsigned payloadType) { // TODO : only manage a list? for (const auto& accountCodec : audio_codec_list_) { if (accountCodec->payloadType == payloadType) return accountCodec; } for (const auto& accountCodec : video_codec_list_) { if (accountCodec->payloadType == payloadType) return accountCodec; } return nullptr; } static void randomFill(std::vector<uint8_t>& dest) { std::uniform_int_distribution<int> rand_byte {0, std::numeric_limits<uint8_t>::max()}; std::random_device rdev; std::generate(dest.begin(), dest.end(), std::bind(rand_byte, std::ref(rdev))); } void Sdp::setActiveLocalSdpSession(const pjmedia_sdp_session* sdp) { if (activeLocalSession_ != sdp) JAMI_DBG("Set active local session to [%p]. Was [%p]", sdp, activeLocalSession_); activeLocalSession_ = sdp; } void Sdp::setActiveRemoteSdpSession(const pjmedia_sdp_session* sdp) { if (activeLocalSession_ != sdp) JAMI_DBG("Set active remote session to [%p]. Was [%p]", sdp, activeRemoteSession_); activeRemoteSession_ = sdp; } pjmedia_sdp_attr* Sdp::generateSdesAttribute() { static constexpr const unsigned cryptoSuite = 0; std::vector<uint8_t> keyAndSalt; keyAndSalt.resize(jami::CryptoSuites[cryptoSuite].masterKeyLength / 8 + jami::CryptoSuites[cryptoSuite].masterSaltLength / 8); // generate keys randomFill(keyAndSalt); std::string crypto_attr = "1 "s + jami::CryptoSuites[cryptoSuite].name + " inline:" + base64::encode(keyAndSalt); pj_str_t val {sip_utils::CONST_PJ_STR(crypto_attr)}; return pjmedia_sdp_attr_create(memPool_.get(), "crypto", &val); } char const* Sdp::mediaDirection(const MediaAttribute& mediaAttr) { if (not mediaAttr.enabled_) { return DIRECTION_STR[MediaDirection::INACTIVE]; } // Since mute/un-mute audio is only done locally (RTP packets // are still sent to the peer), the media direction must be // set to "sendrecv" regardless of the mute state. if (mediaAttr.type_ == MediaType::MEDIA_AUDIO) { return DIRECTION_STR[MediaDirection::SENDRECV]; } if (mediaAttr.muted_) { if (mediaAttr.onHold_) { return DIRECTION_STR[MediaDirection::INACTIVE]; } return DIRECTION_STR[MediaDirection::RECVONLY]; } if (mediaAttr.onHold_) { return DIRECTION_STR[MediaDirection::SENDONLY]; } return DIRECTION_STR[MediaDirection::SENDRECV]; } MediaDirection Sdp::getMediaDirection(pjmedia_sdp_media* media) { if (pjmedia_sdp_attr_find2(media->attr_count, media->attr, DIRECTION_STR[MediaDirection::SENDRECV], nullptr) != nullptr) { return MediaDirection::SENDRECV; } if (pjmedia_sdp_attr_find2(media->attr_count, media->attr, DIRECTION_STR[MediaDirection::SENDONLY], nullptr) != nullptr) { return MediaDirection::SENDONLY; } if (pjmedia_sdp_attr_find2(media->attr_count, media->attr, DIRECTION_STR[MediaDirection::RECVONLY], nullptr) != nullptr) { return MediaDirection::RECVONLY; } if (pjmedia_sdp_attr_find2(media->attr_count, media->attr, DIRECTION_STR[MediaDirection::INACTIVE], nullptr) != nullptr) { return MediaDirection::INACTIVE; } return MediaDirection::UNKNOWN; } MediaTransport Sdp::getMediaTransport(pjmedia_sdp_media* media) { if (pj_stricmp2(&media->desc.transport, "RTP/SAVP") == 0) return MediaTransport::RTP_SAVP; else if (pj_stricmp2(&media->desc.transport, "RTP/AVP") == 0) return MediaTransport::RTP_AVP; return MediaTransport::UNKNOWN; } std::vector<std::string> Sdp::getCrypto(pjmedia_sdp_media* media) { std::vector<std::string> crypto; for (unsigned j = 0; j < media->attr_count; j++) { const auto attribute = media->attr[j]; if (pj_stricmp2(&attribute->name, "crypto") == 0) crypto.emplace_back(attribute->value.ptr, attribute->value.slen); } return crypto; } pjmedia_sdp_media* Sdp::addMediaDescription(const MediaAttribute& mediaAttr) { auto type = mediaAttr.type_; auto secure = mediaAttr.secure_; JAMI_DBG("Add media description [%s]", mediaAttr.toString(true).c_str()); pjmedia_sdp_media* med = PJ_POOL_ZALLOC_T(memPool_.get(), pjmedia_sdp_media); switch (type) { case MediaType::MEDIA_AUDIO: med->desc.media = sip_utils::CONST_PJ_STR("audio"); med->desc.port = mediaAttr.enabled_ ? localAudioRtpPort_ : 0; med->desc.fmt_count = audio_codec_list_.size(); break; case MediaType::MEDIA_VIDEO: med->desc.media = sip_utils::CONST_PJ_STR("video"); med->desc.port = mediaAttr.enabled_ ? localVideoRtpPort_ : 0; med->desc.fmt_count = video_codec_list_.size(); break; default: throw SdpException("Unsupported media type! Only audio and video are supported"); break; } med->desc.port_count = 1; // Set the transport protocol of the media med->desc.transport = secure ? sip_utils::CONST_PJ_STR("RTP/SAVP") : sip_utils::CONST_PJ_STR("RTP/AVP"); unsigned dynamic_payload = 96; for (unsigned i = 0; i < med->desc.fmt_count; i++) { pjmedia_sdp_rtpmap rtpmap; rtpmap.param.slen = 0; std::string channels; // must have the lifetime of rtpmap std::string enc_name; unsigned payload; if (type == MediaType::MEDIA_AUDIO) { auto accountAudioCodec = std::static_pointer_cast<SystemAudioCodecInfo>( audio_codec_list_[i]); payload = accountAudioCodec->payloadType; enc_name = accountAudioCodec->name; if (accountAudioCodec->audioformat.nb_channels > 1) { channels = std::to_string(accountAudioCodec->audioformat.nb_channels); rtpmap.param = sip_utils::CONST_PJ_STR(channels); } // G722 requires G722/8000 media description even though it's @ 16000 Hz // See http://tools.ietf.org/html/rfc3551#section-4.5.2 if (accountAudioCodec->isPCMG722()) rtpmap.clock_rate = 8000; else rtpmap.clock_rate = accountAudioCodec->audioformat.sample_rate; } else { // FIXME: get this key from header payload = dynamic_payload++; enc_name = video_codec_list_[i]->name; rtpmap.clock_rate = 90000; } auto payloadStr = std::to_string(payload); auto pjPayload = sip_utils::CONST_PJ_STR(payloadStr); pj_strdup(memPool_.get(), &med->desc.fmt[i], &pjPayload); // Add a rtpmap field for each codec // We could add one only for dynamic payloads because the codecs with static RTP payloads // are entirely defined in the RFC 3351 rtpmap.pt = med->desc.fmt[i]; rtpmap.enc_name = sip_utils::CONST_PJ_STR(enc_name); pjmedia_sdp_attr* attr; pjmedia_sdp_rtpmap_to_attr(memPool_.get(), &rtpmap, &attr); med->attr[med->attr_count++] = attr; #ifdef ENABLE_VIDEO if (enc_name == "H264") { // FIXME: this should not be hardcoded, it will determine what profile and level // our peer will send us const auto accountVideoCodec = std::static_pointer_cast<SystemVideoCodecInfo>( video_codec_list_[i]); const auto& profileLevelID = accountVideoCodec->parameters.empty() ? libav_utils::DEFAULT_H264_PROFILE_LEVEL_ID : accountVideoCodec->parameters; auto value = fmt::format("fmtp:{} {}", payload, profileLevelID); med->attr[med->attr_count++] = pjmedia_sdp_attr_create(memPool_.get(), value.c_str(), NULL); } #endif } if (type == MediaType::MEDIA_AUDIO) { setTelephoneEventRtpmap(med); if (localAudioRtcpPort_) { addRTCPAttribute(med, localAudioRtcpPort_); } } else if (type == MediaType::MEDIA_VIDEO and localVideoRtcpPort_) { addRTCPAttribute(med, localVideoRtcpPort_); } char const* direction = mediaDirection(mediaAttr); med->attr[med->attr_count++] = pjmedia_sdp_attr_create(memPool_.get(), direction, NULL); if (secure) { if (pjmedia_sdp_media_add_attr(med, generateSdesAttribute()) != PJ_SUCCESS) throw SdpException("Unable to add sdes attribute to media"); } return med; } void Sdp::addRTCPAttribute(pjmedia_sdp_media* med, uint16_t port) { dhtnet::IpAddr addr {publishedIpAddr_}; addr.setPort(port); pjmedia_sdp_attr* attr = pjmedia_sdp_attr_create_rtcp(memPool_.get(), addr.pjPtr()); if (attr) pjmedia_sdp_attr_add(&med->attr_count, med->attr, attr); } void Sdp::setPublishedIP(const std::string& addr, pj_uint16_t addr_type) { publishedIpAddr_ = addr; publishedIpAddrType_ = addr_type; if (localSession_) { if (addr_type == pj_AF_INET6()) localSession_->origin.addr_type = sip_utils::CONST_PJ_STR("IP6"); else localSession_->origin.addr_type = sip_utils::CONST_PJ_STR("IP4"); localSession_->origin.addr = sip_utils::CONST_PJ_STR(publishedIpAddr_); localSession_->conn->addr = localSession_->origin.addr; if (pjmedia_sdp_validate(localSession_) != PJ_SUCCESS) JAMI_ERR("Unable to validate SDP"); } } void Sdp::setPublishedIP(const dhtnet::IpAddr& ip_addr) { setPublishedIP(ip_addr, ip_addr.getFamily()); } void Sdp::setTelephoneEventRtpmap(pjmedia_sdp_media* med) { ++med->desc.fmt_count; pj_strdup2(memPool_.get(), &med->desc.fmt[med->desc.fmt_count - 1], std::to_string(telephoneEventPayload_).c_str()); pjmedia_sdp_attr* attr_rtpmap = static_cast<pjmedia_sdp_attr*>( pj_pool_zalloc(memPool_.get(), sizeof(pjmedia_sdp_attr))); attr_rtpmap->name = sip_utils::CONST_PJ_STR("rtpmap"); attr_rtpmap->value = sip_utils::CONST_PJ_STR("101 telephone-event/8000"); med->attr[med->attr_count++] = attr_rtpmap; pjmedia_sdp_attr* attr_fmtp = static_cast<pjmedia_sdp_attr*>( pj_pool_zalloc(memPool_.get(), sizeof(pjmedia_sdp_attr))); attr_fmtp->name = sip_utils::CONST_PJ_STR("fmtp"); attr_fmtp->value = sip_utils::CONST_PJ_STR("101 0-15"); med->attr[med->attr_count++] = attr_fmtp; } void Sdp::setLocalMediaCapabilities(MediaType type, const std::vector<std::shared_ptr<SystemCodecInfo>>& selectedCodecs) { switch (type) { case MediaType::MEDIA_AUDIO: audio_codec_list_ = selectedCodecs; break; case MediaType::MEDIA_VIDEO: #ifdef ENABLE_VIDEO video_codec_list_ = selectedCodecs; // Do not expose H265 if accel is disactivated if (not jami::Manager::instance().videoPreferences.getEncodingAccelerated()) { video_codec_list_.erase(std::remove_if(video_codec_list_.begin(), video_codec_list_.end(), [](const std::shared_ptr<SystemCodecInfo>& i) { return i->name == "H265"; }), video_codec_list_.end()); } #else (void) selectedCodecs; #endif break; default: throw SdpException("Unsupported media type"); break; } } const char* Sdp::getSdpDirectionStr(SdpDirection direction) { if (direction == SdpDirection::OFFER) return "OFFER"; if (direction == SdpDirection::ANSWER) return "ANSWER"; return "NONE"; } void Sdp::printSession(const pjmedia_sdp_session* session, const char* header, SdpDirection direction) { static constexpr size_t BUF_SZ = 4095; std::unique_ptr<pj_pool_t, decltype(pj_pool_release)&> tmpPool_(pj_pool_create(&Manager::instance().sipVoIPLink().getCachingPool()->factory, "printSdp", BUF_SZ, BUF_SZ, nullptr), pj_pool_release); auto cloned_session = pjmedia_sdp_session_clone(tmpPool_.get(), session); if (!cloned_session) { JAMI_ERR("Unable to clone SDP for printing"); return; } // Filter-out sensible data like SRTP master key. for (unsigned i = 0; i < cloned_session->media_count; ++i) { pjmedia_sdp_media_remove_all_attr(cloned_session->media[i], "crypto"); } std::array<char, BUF_SZ + 1> buffer; auto size = pjmedia_sdp_print(cloned_session, buffer.data(), BUF_SZ); if (size < 0) { JAMI_ERR("%s SDP too big for dump", header); return; } JAMI_DBG("[SDP %s] %s\n%.*s", getSdpDirectionStr(direction), header, size, buffer.data()); } void Sdp::createLocalSession(SdpDirection direction) { sdpDirection_ = direction; localSession_ = PJ_POOL_ZALLOC_T(memPool_.get(), pjmedia_sdp_session); localSession_->conn = PJ_POOL_ZALLOC_T(memPool_.get(), pjmedia_sdp_conn); /* Initialize the fields of the struct */ localSession_->origin.version = 0; pj_time_val tv; pj_gettimeofday(&tv); localSession_->origin.user = *pj_gethostname(); // Use Network Time Protocol format timestamp to ensure uniqueness. localSession_->origin.id = tv.sec + 2208988800UL; localSession_->origin.net_type = sip_utils::CONST_PJ_STR("IN"); if (publishedIpAddrType_ == pj_AF_INET6()) localSession_->origin.addr_type = sip_utils::CONST_PJ_STR("IP6"); else localSession_->origin.addr_type = sip_utils::CONST_PJ_STR("IP4"); localSession_->origin.addr = sip_utils::CONST_PJ_STR(publishedIpAddr_); // Use the call IDs for s= line localSession_->name = sip_utils::CONST_PJ_STR(sessionName_); localSession_->conn->net_type = localSession_->origin.net_type; localSession_->conn->addr_type = localSession_->origin.addr_type; localSession_->conn->addr = localSession_->origin.addr; // RFC 3264: An offer/answer model session description protocol // As the session is created and destroyed through an external signaling mean (SIP), the line // should have a value of "0 0". localSession_->time.start = 0; localSession_->time.stop = 0; } int Sdp::validateSession() const { return pjmedia_sdp_validate(localSession_); } bool Sdp::createOffer(const std::vector<MediaAttribute>& mediaList) { if (mediaList.size() >= PJMEDIA_MAX_SDP_MEDIA) { throw SdpException("Media list size exceeds SDP media maximum size"); } JAMI_DEBUG("Creating SDP offer with {} media", mediaList.size()); createLocalSession(SdpDirection::OFFER); if (validateSession() != PJ_SUCCESS) { JAMI_ERR("Failed to create initial offer"); return false; } localSession_->media_count = 0; for (auto const& media : mediaList) { if (media.enabled_) { localSession_->media[localSession_->media_count++] = addMediaDescription(media); } } if (validateSession() != PJ_SUCCESS) { JAMI_ERR("Failed to add medias"); return false; } if (pjmedia_sdp_neg_create_w_local_offer(memPool_.get(), localSession_, &negotiator_) != PJ_SUCCESS) { JAMI_ERR("Failed to create an initial SDP negotiator"); return false; } printSession(localSession_, "Local session (initial):", sdpDirection_); return true; } void Sdp::setReceivedOffer(const pjmedia_sdp_session* remote) { if (remote == nullptr) { JAMI_ERR("Remote session is NULL"); return; } remoteSession_ = pjmedia_sdp_session_clone(memPool_.get(), remote); } bool Sdp::processIncomingOffer(const std::vector<MediaAttribute>& mediaList) { if (not remoteSession_) return false; JAMI_DEBUG("Processing received offer for [{:s}] with {:d} media", sessionName_, mediaList.size()); printSession(remoteSession_, "Remote session:", SdpDirection::OFFER); createLocalSession(SdpDirection::ANSWER); if (validateSession() != PJ_SUCCESS) { JAMI_ERR("Failed to create local session"); return false; } localSession_->media_count = 0; for (auto const& media : mediaList) { if (media.enabled_) { localSession_->media[localSession_->media_count++] = addMediaDescription(media); } } printSession(localSession_, "Local session:\n", sdpDirection_); if (validateSession() != PJ_SUCCESS) { JAMI_ERR("Failed to add medias"); return false; } if (pjmedia_sdp_neg_create_w_remote_offer(memPool_.get(), localSession_, remoteSession_, &negotiator_) != PJ_SUCCESS) { JAMI_ERR("Failed to initialize media negotiation"); return false; } return true; } bool Sdp::startNegotiation() { JAMI_DBG("Starting media negotiation for [%s]", sessionName_.c_str()); if (negotiator_ == NULL) { JAMI_ERR("Unable to start negotiation with invalid negotiator"); return false; } const pjmedia_sdp_session* active_local; const pjmedia_sdp_session* active_remote; if (pjmedia_sdp_neg_get_state(negotiator_) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) { JAMI_WARN("Negotiator not in right state for negotiation"); return false; } if (pjmedia_sdp_neg_negotiate(memPool_.get(), negotiator_, 0) != PJ_SUCCESS) { JAMI_ERR("Failed to start media negotiation"); return false; } if (pjmedia_sdp_neg_get_active_local(negotiator_, &active_local) != PJ_SUCCESS) JAMI_ERR("Unable to retrieve local active session"); setActiveLocalSdpSession(active_local); if (active_local != nullptr) { printSession(active_local, "Local active session:", sdpDirection_); } if (pjmedia_sdp_neg_get_active_remote(negotiator_, &active_remote) != PJ_SUCCESS or active_remote == nullptr) { JAMI_ERR("Unable to retrieve remote active session"); return false; } setActiveRemoteSdpSession(active_remote); printSession(active_remote, "Remote active session:", sdpDirection_); return true; } std::string Sdp::getFilteredSdp(const pjmedia_sdp_session* session, unsigned media_keep, unsigned pt_keep) { static constexpr size_t BUF_SZ = 4096; std::unique_ptr<pj_pool_t, decltype(pj_pool_release)&> tmpPool_(pj_pool_create(&Manager::instance().sipVoIPLink().getCachingPool()->factory, "tmpSdp", BUF_SZ, BUF_SZ, nullptr), pj_pool_release); auto cloned = pjmedia_sdp_session_clone(tmpPool_.get(), session); if (!cloned) { JAMI_ERR("Unable to clone SDP"); return ""; } // deactivate non-video media bool hasKeep = false; for (unsigned i = 0; i < cloned->media_count; i++) if (i != media_keep) { if (pjmedia_sdp_media_deactivate(tmpPool_.get(), cloned->media[i]) != PJ_SUCCESS) JAMI_ERR("Unable to deactivate media"); } else { hasKeep = true; } if (not hasKeep) { JAMI_DBG("No media to keep present in SDP"); return ""; } // Leaking medias will be dropped with tmpPool_ for (unsigned i = 0; i < cloned->media_count; i++) if (cloned->media[i]->desc.port == 0) { std::move(cloned->media + i + 1, cloned->media + cloned->media_count, cloned->media + i); cloned->media_count--; i--; } for (unsigned i = 0; i < cloned->media_count; i++) { auto media = cloned->media[i]; // filter other codecs for (unsigned c = 0; c < media->desc.fmt_count; c++) { auto& pt = media->desc.fmt[c]; if (pj_strtoul(&pt) == pt_keep) continue; while (auto attr = pjmedia_sdp_attr_find2(media->attr_count, media->attr, "rtpmap", &pt)) pjmedia_sdp_attr_remove(&media->attr_count, media->attr, attr); while (auto attr = pjmedia_sdp_attr_find2(media->attr_count, media->attr, "fmt", &pt)) pjmedia_sdp_attr_remove(&media->attr_count, media->attr, attr); std::move(media->desc.fmt + c + 1, media->desc.fmt + media->desc.fmt_count, media->desc.fmt + c); media->desc.fmt_count--; c--; } // we handle crypto ourselfs, don't tell libav about it pjmedia_sdp_media_remove_all_attr(media, "crypto"); } char buffer[BUF_SZ]; size_t size = pjmedia_sdp_print(cloned, buffer, sizeof(buffer)); string sessionStr(buffer, std::min(size, sizeof(buffer))); return sessionStr; } std::vector<MediaDescription> Sdp::getActiveMediaDescription(bool remote) const { if (remote) return getMediaDescriptions(activeRemoteSession_, true); return getMediaDescriptions(activeLocalSession_, false); } std::vector<MediaDescription> Sdp::getMediaDescriptions(const pjmedia_sdp_session* session, bool remote) const { if (!session) return {}; static constexpr pj_str_t STR_RTPMAP {sip_utils::CONST_PJ_STR("rtpmap")}; static constexpr pj_str_t STR_FMTP {sip_utils::CONST_PJ_STR("fmtp")}; std::vector<MediaDescription> ret; for (unsigned i = 0; i < session->media_count; i++) { auto media = session->media[i]; ret.emplace_back(MediaDescription()); MediaDescription& descr = ret.back(); if (!pj_stricmp2(&media->desc.media, "audio")) descr.type = MEDIA_AUDIO; else if (!pj_stricmp2(&media->desc.media, "video")) descr.type = MEDIA_VIDEO; else continue; descr.enabled = media->desc.port; if (!descr.enabled) continue; // get connection info pjmedia_sdp_conn* conn = media->conn ? media->conn : session->conn; if (not conn) { JAMI_ERR("Unable to find connection information for media"); continue; } descr.addr = std::string_view(conn->addr.ptr, conn->addr.slen); descr.addr.setPort(media->desc.port); // Get the "rtcp" address from the SDP if present. Otherwise, // infere it from endpoint (RTP) address. auto attr = pjmedia_sdp_attr_find2(media->attr_count, media->attr, "rtcp", NULL); if (attr) { pjmedia_sdp_rtcp_attr rtcp; auto status = pjmedia_sdp_attr_get_rtcp(attr, &rtcp); if (status == PJ_SUCCESS && rtcp.addr.slen) { descr.rtcp_addr = std::string_view(rtcp.addr.ptr, rtcp.addr.slen); descr.rtcp_addr.setPort(rtcp.port); } } descr.onHold = pjmedia_sdp_attr_find2(media->attr_count, media->attr, DIRECTION_STR[MediaDirection::SENDONLY], nullptr) || pjmedia_sdp_attr_find2(media->attr_count, media->attr, DIRECTION_STR[MediaDirection::INACTIVE], nullptr); descr.direction_ = getMediaDirection(media); if (descr.direction_ == MediaDirection::UNKNOWN) { JAMI_ERR("Did not find media direction attribute in remote SDP"); } // get codecs infos for (unsigned j = 0; j < media->desc.fmt_count; j++) { const auto rtpMapAttribute = pjmedia_sdp_media_find_attr(media, &STR_RTPMAP, &media->desc.fmt[j]); if (!rtpMapAttribute) { JAMI_ERR("Unable to find rtpmap attribute"); descr.enabled = false; continue; } pjmedia_sdp_rtpmap rtpmap; if (pjmedia_sdp_attr_get_rtpmap(rtpMapAttribute, &rtpmap) != PJ_SUCCESS || rtpmap.enc_name.slen == 0) { JAMI_ERR("Unable to find payload type %.*s in SDP", (int) media->desc.fmt[j].slen, media->desc.fmt[j].ptr); descr.enabled = false; continue; } auto codec_raw = sip_utils::as_view(rtpmap.enc_name); descr.rtp_clockrate = rtpmap.clock_rate; descr.codec = findCodecBySpec(codec_raw, rtpmap.clock_rate); if (not descr.codec) { JAMI_ERR("Unable to find codec %.*s", (int) codec_raw.size(), codec_raw.data()); descr.enabled = false; continue; } descr.payload_type = pj_strtoul(&rtpmap.pt); if (descr.type == MEDIA_VIDEO) { const auto fmtpAttr = pjmedia_sdp_media_find_attr(media, &STR_FMTP, &media->desc.fmt[j]); // descr.bitrate = getOutgoingVideoField(codec, "bitrate"); if (fmtpAttr && fmtpAttr->value.ptr && fmtpAttr->value.slen) { const auto& v = fmtpAttr->value; descr.parameters = std::string(v.ptr, v.ptr + v.slen); } } // for now, just keep the first codec only descr.enabled = true; break; } if (not remote) descr.receiving_sdp = getFilteredSdp(session, i, descr.payload_type); // get crypto info std::vector<std::string> crypto; for (unsigned j = 0; j < media->attr_count; j++) { const auto attribute = media->attr[j]; if (pj_stricmp2(&attribute->name, "crypto") == 0) crypto.emplace_back(attribute->value.ptr, attribute->value.slen); } descr.crypto = SdesNegotiator::negotiate(crypto); } return ret; } std::vector<Sdp::MediaSlot> Sdp::getMediaSlots() const { auto loc = getMediaDescriptions(activeLocalSession_, false); auto rem = getMediaDescriptions(activeRemoteSession_, true); size_t slot_n = std::min(loc.size(), rem.size()); std::vector<MediaSlot> s; s.reserve(slot_n); for (decltype(slot_n) i = 0; i < slot_n; i++) s.emplace_back(std::move(loc[i]), std::move(rem[i])); return s; } void Sdp::addIceCandidates(unsigned media_index, const std::vector<std::string>& cands) { if (media_index >= localSession_->media_count) { JAMI_ERR("addIceCandidates failed: unable to access media#%u (may be deactivated)", media_index); return; } auto media = localSession_->media[media_index]; for (const auto& item : cands) { const pj_str_t val = sip_utils::CONST_PJ_STR(item); pjmedia_sdp_attr* attr = pjmedia_sdp_attr_create(memPool_.get(), "candidate", &val); if (pjmedia_sdp_media_add_attr(media, attr) != PJ_SUCCESS) throw SdpException("Unable to add ICE candidates attribute to media"); } } std::vector<std::string> Sdp::getIceCandidates(unsigned media_index) const { auto remoteSession = activeRemoteSession_ ? activeRemoteSession_ : remoteSession_; auto localSession = activeLocalSession_ ? activeLocalSession_ : localSession_; if (not remoteSession) { JAMI_ERR("getIceCandidates failed: no remote session"); return {}; } if (not localSession) { JAMI_ERR("getIceCandidates failed: no local session"); return {}; } if (media_index >= remoteSession->media_count || media_index >= localSession->media_count) { JAMI_ERR("getIceCandidates failed: unable to access media#%u (may be deactivated)", media_index); return {}; } auto media = remoteSession->media[media_index]; auto localMedia = localSession->media[media_index]; if (media->desc.port == 0 || localMedia->desc.port == 0) { JAMI_WARN("Media#%u is disabled. Media ports: local %u, remote %u", media_index, localMedia->desc.port, media->desc.port); return {}; } std::vector<std::string> candidates; for (unsigned i = 0; i < media->attr_count; i++) { pjmedia_sdp_attr* attribute = media->attr[i]; if (pj_stricmp2(&attribute->name, "candidate") == 0) candidates.push_back(std::string(attribute->value.ptr, attribute->value.slen)); } return candidates; } void Sdp::addIceAttributes(const dhtnet::IceTransport::Attribute&& ice_attrs) { pj_str_t value = sip_utils::CONST_PJ_STR(ice_attrs.ufrag); pjmedia_sdp_attr* attr = pjmedia_sdp_attr_create(memPool_.get(), "ice-ufrag", &value); if (pjmedia_sdp_attr_add(&localSession_->attr_count, localSession_->attr, attr) != PJ_SUCCESS) throw SdpException("Unable to add ICE.ufrag attribute to local SDP"); value = sip_utils::CONST_PJ_STR(ice_attrs.pwd); attr = pjmedia_sdp_attr_create(memPool_.get(), "ice-pwd", &value); if (pjmedia_sdp_attr_add(&localSession_->attr_count, localSession_->attr, attr) != PJ_SUCCESS) throw SdpException("Unable to add ICE.pwd attribute to local SDP"); } dhtnet::IceTransport::Attribute Sdp::getIceAttributes() const { if (auto session = activeRemoteSession_ ? activeRemoteSession_ : remoteSession_) return getIceAttributes(session); return {}; } dhtnet::IceTransport::Attribute Sdp::getIceAttributes(const pjmedia_sdp_session* session) { dhtnet::IceTransport::Attribute ice_attrs; // Per RFC8839, ice-ufrag/ice-pwd can be present either at // media or session level. // This seems to be the case for Asterisk servers (ICE is at media-session). for (unsigned i = 0; i < session->attr_count; i++) { pjmedia_sdp_attr* attribute = session->attr[i]; if (pj_stricmp2(&attribute->name, "ice-ufrag") == 0) ice_attrs.ufrag.assign(attribute->value.ptr, attribute->value.slen); else if (pj_stricmp2(&attribute->name, "ice-pwd") == 0) ice_attrs.pwd.assign(attribute->value.ptr, attribute->value.slen); if (!ice_attrs.ufrag.empty() && !ice_attrs.pwd.empty()) return ice_attrs; } for (unsigned i = 0; i < session->media_count; i++) { auto* media = session->media[i]; for (unsigned j = 0; j < media->attr_count; j++) { pjmedia_sdp_attr* attribute = media->attr[j]; if (pj_stricmp2(&attribute->name, "ice-ufrag") == 0) ice_attrs.ufrag.assign(attribute->value.ptr, attribute->value.slen); else if (pj_stricmp2(&attribute->name, "ice-pwd") == 0) ice_attrs.pwd.assign(attribute->value.ptr, attribute->value.slen); if (!ice_attrs.ufrag.empty() && !ice_attrs.pwd.empty()) return ice_attrs; } } return ice_attrs; } void Sdp::clearIce() { clearIce(localSession_); clearIce(remoteSession_); setActiveRemoteSdpSession(nullptr); setActiveLocalSdpSession(nullptr); } void Sdp::clearIce(pjmedia_sdp_session* session) { if (not session) return; pjmedia_sdp_attr_remove_all(&session->attr_count, session->attr, "ice-ufrag"); pjmedia_sdp_attr_remove_all(&session->attr_count, session->attr, "ice-pwd"); // TODO. Why this? we should not have "candidate" attribute at session level. pjmedia_sdp_attr_remove_all(&session->attr_count, session->attr, "candidate"); for (unsigned i = 0; i < session->media_count; i++) { auto media = session->media[i]; pjmedia_sdp_attr_remove_all(&media->attr_count, media->attr, "candidate"); } } std::vector<MediaAttribute> Sdp::getMediaAttributeListFromSdp(const pjmedia_sdp_session* sdpSession, bool ignoreDisabled) { if (sdpSession == nullptr) { return {}; } std::vector<MediaAttribute> mediaList; unsigned audioIdx = 0; unsigned videoIdx = 0; for (unsigned idx = 0; idx < sdpSession->media_count; idx++) { mediaList.emplace_back(MediaAttribute {}); auto& mediaAttr = mediaList.back(); auto const& media = sdpSession->media[idx]; // Get media type. if (!pj_stricmp2(&media->desc.media, "audio")) mediaAttr.type_ = MediaType::MEDIA_AUDIO; else if (!pj_stricmp2(&media->desc.media, "video")) mediaAttr.type_ = MediaType::MEDIA_VIDEO; else { JAMI_WARN("Media#%u only 'audio' and 'video' types are supported!", idx); // Disable the media. No need to parse the attributes. mediaAttr.enabled_ = false; continue; } // Set enabled flag mediaAttr.enabled_ = media->desc.port > 0; if (!mediaAttr.enabled_ && ignoreDisabled) { mediaList.pop_back(); continue; } // Get mute state. auto direction = getMediaDirection(media); mediaAttr.muted_ = direction != MediaDirection::SENDRECV and direction != MediaDirection::SENDONLY; // Get transport. auto transp = getMediaTransport(media); if (transp == MediaTransport::UNKNOWN) { JAMI_WARN("Media#%u is unable to determine transport type!", idx); } // A media is secure if the transport is of type RTP/SAVP // and the crypto materials are present. mediaAttr.secure_ = transp == MediaTransport::RTP_SAVP and not getCrypto(media).empty(); if (mediaAttr.type_ == MediaType::MEDIA_AUDIO) { mediaAttr.label_ = "audio_" + std::to_string(audioIdx++); } else if (mediaAttr.type_ == MediaType::MEDIA_VIDEO) { mediaAttr.label_ = "video_" + std::to_string(videoIdx++); } } return mediaList; } } // namespace jami
38,285
C++
.cpp
920
32.445652
103
0.603409
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,832
siptransport.cpp
savoirfairelinux_jami-daemon/src/sip/siptransport.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sip/siptransport.h" #include "connectivity/sip_utils.h" #include "jamidht/abstract_sip_transport.h" #include "jamidht/channeled_transport.h" #include "compiler_intrinsics.h" #include "sip/sipvoiplink.h" #include <pjsip.h> #include <pjsip/sip_types.h> #include <pjsip/sip_transport_tls.h> #include <pj/ssl_sock.h> #include <pjnath.h> #include <pjnath/stun_config.h> #include <pjlib.h> #include <pjlib-util.h> #include <dhtnet/multiplexed_socket.h> #include <dhtnet/ip_utils.h> #include <dhtnet/tls_session.h> #include <opendht/crypto.h> #include <stdexcept> #include <sstream> #include <algorithm> #define RETURN_IF_FAIL(A, VAL, ...) \ if (!(A)) { \ JAMI_ERR(__VA_ARGS__); \ return (VAL); \ } namespace jami { constexpr const char* TRANSPORT_STATE_STR[] = {"CONNECTED", "DISCONNECTED", "SHUTDOWN", "DESTROY", "UNKNOWN STATE"}; constexpr const size_t TRANSPORT_STATE_SZ = std::size(TRANSPORT_STATE_STR); void SipTransport::deleteTransport(pjsip_transport* t) { pjsip_transport_dec_ref(t); } SipTransport::SipTransport(pjsip_transport* t) : transport_(nullptr, deleteTransport) { if (not t or pjsip_transport_add_ref(t) != PJ_SUCCESS) throw std::runtime_error("invalid transport"); // Set pointer here, right after the successful pjsip_transport_add_ref transport_.reset(t); JAMI_DEBUG("SipTransport@{} tr={} rc={:d}", fmt::ptr(this), fmt::ptr(transport_.get()), pj_atomic_get(transport_->ref_cnt)); } SipTransport::SipTransport(pjsip_transport* t, const std::shared_ptr<TlsListener>& l) : SipTransport(t) { tlsListener_ = l; } SipTransport::SipTransport(pjsip_transport* t, const std::shared_ptr<dht::crypto::Certificate>& peerCertficate) : SipTransport(t) { tlsInfos_.peerCert = peerCertficate; } SipTransport::~SipTransport() { JAMI_DEBUG("~SipTransport@{} tr={} rc={:d}", fmt::ptr(this), fmt::ptr(transport_.get()), pj_atomic_get(transport_->ref_cnt)); } bool SipTransport::isAlive(pjsip_transport_state state) { return state != PJSIP_TP_STATE_DISCONNECTED && state != PJSIP_TP_STATE_SHUTDOWN && state != PJSIP_TP_STATE_DESTROY; } const char* SipTransport::stateToStr(pjsip_transport_state state) { return TRANSPORT_STATE_STR[std::min<size_t>(state, TRANSPORT_STATE_SZ - 1)]; } void SipTransport::stateCallback(pjsip_transport_state state, const pjsip_transport_state_info* info) { connected_ = state == PJSIP_TP_STATE_CONNECTED; auto extInfo = static_cast<const pjsip_tls_state_info*>(info->ext_info); if (isSecure() && extInfo && extInfo->ssl_sock_info && extInfo->ssl_sock_info->established) { auto tlsInfo = extInfo->ssl_sock_info; tlsInfos_.proto = (pj_ssl_sock_proto) tlsInfo->proto; tlsInfos_.cipher = tlsInfo->cipher; tlsInfos_.verifyStatus = (pj_ssl_cert_verify_flag_t) tlsInfo->verify_status; if (!tlsInfos_.peerCert) { const auto& peers = tlsInfo->remote_cert_info->raw_chain; std::vector<std::pair<const uint8_t*, const uint8_t*>> bits; bits.resize(peers.cnt); std::transform(peers.cert_raw, peers.cert_raw + peers.cnt, std::begin(bits), [](const pj_str_t& crt) { return std::make_pair((uint8_t*) crt.ptr, (uint8_t*) (crt.ptr + crt.slen)); }); tlsInfos_.peerCert = std::make_shared<dht::crypto::Certificate>(bits); } } else { tlsInfos_ = {}; } std::vector<SipTransportStateCallback> cbs; { std::lock_guard lock(stateListenersMutex_); cbs.reserve(stateListeners_.size()); for (auto& l : stateListeners_) cbs.push_back(l.second); } for (auto& cb : cbs) cb(state, info); } void SipTransport::addStateListener(uintptr_t lid, SipTransportStateCallback cb) { std::lock_guard lock(stateListenersMutex_); auto pair = stateListeners_.insert(std::make_pair(lid, cb)); if (not pair.second) pair.first->second = cb; } bool SipTransport::removeStateListener(uintptr_t lid) { std::lock_guard lock(stateListenersMutex_); auto it = stateListeners_.find(lid); if (it != stateListeners_.end()) { stateListeners_.erase(it); return true; } return false; } uint16_t SipTransport::getTlsMtu() { return 1232; /* Hardcoded yes (it's the IPv6 value). * This method is broken by definition. * A MTU should not be defined at this layer. * And a correct value should come from the underlying transport itself, * not from a constant... */ } SipTransportBroker::SipTransportBroker(pjsip_endpoint* endpt) : endpt_(endpt) {} SipTransportBroker::~SipTransportBroker() { shutdown(); udpTransports_.clear(); transports_.clear(); JAMI_DBG("destroying SipTransportBroker@%p", this); } void SipTransportBroker::transportStateChanged(pjsip_transport* tp, pjsip_transport_state state, const pjsip_transport_state_info* info) { JAMI_DBG("pjsip transport@%p %s -> %s", tp, tp->info, SipTransport::stateToStr(state)); // First make sure that this transport is handled by us // and remove it from any mapping if destroy pending or done. std::shared_ptr<SipTransport> sipTransport; std::lock_guard lock(transportMapMutex_); auto key = transports_.find(tp); if (key == transports_.end()) return; sipTransport = key->second.lock(); if (!isDestroying_ && state == PJSIP_TP_STATE_DESTROY) { // maps cleanup JAMI_DBG("unmap pjsip transport@%p {SipTransport@%p}", tp, sipTransport.get()); transports_.erase(key); // If UDP const auto type = tp->key.type; if (type == PJSIP_TRANSPORT_UDP or type == PJSIP_TRANSPORT_UDP6) { const auto updKey = std::find_if(udpTransports_.cbegin(), udpTransports_.cend(), [tp](const std::pair<dhtnet::IpAddr, pjsip_transport*>& pair) { return pair.second == tp; }); if (updKey != udpTransports_.cend()) udpTransports_.erase(updKey); } } // Propagate the event to the appropriate transport // Note the SipTransport may not be in our mappings if marked as dead if (sipTransport) sipTransport->stateCallback(state, info); } std::shared_ptr<SipTransport> SipTransportBroker::addTransport(pjsip_transport* t) { if (t) { std::lock_guard lock(transportMapMutex_); auto key = transports_.find(t); if (key != transports_.end()) { if (auto sipTr = key->second.lock()) return sipTr; } auto sipTr = std::make_shared<SipTransport>(t); if (key != transports_.end()) key->second = sipTr; else transports_.emplace(std::make_pair(t, sipTr)); return sipTr; } return nullptr; } void SipTransportBroker::shutdown() { std::unique_lock lock(transportMapMutex_); isDestroying_ = true; for (auto& t : transports_) { if (auto transport = t.second.lock()) { pjsip_transport_shutdown(transport->get()); } } } std::shared_ptr<SipTransport> SipTransportBroker::getUdpTransport(const dhtnet::IpAddr& ipAddress) { std::lock_guard lock(transportMapMutex_); auto itp = udpTransports_.find(ipAddress); if (itp != udpTransports_.end()) { auto it = transports_.find(itp->second); if (it != transports_.end()) { if (auto spt = it->second.lock()) { JAMI_DBG("Reusing transport %s", ipAddress.toString(true).c_str()); return spt; } else { // Transport still exists but have not been destroyed yet. JAMI_WARN("Recycling transport %s", ipAddress.toString(true).c_str()); auto ret = std::make_shared<SipTransport>(itp->second); it->second = ret; return ret; } } else { JAMI_WARN("Cleaning up UDP transport %s", ipAddress.toString(true).c_str()); udpTransports_.erase(itp); } } auto ret = createUdpTransport(ipAddress); if (ret) { udpTransports_[ipAddress] = ret->get(); transports_[ret->get()] = ret; } return ret; } std::shared_ptr<SipTransport> SipTransportBroker::createUdpTransport(const dhtnet::IpAddr& ipAddress) { RETURN_IF_FAIL(ipAddress, nullptr, "Unable to determine IP address for this transport"); pjsip_udp_transport_cfg pj_cfg; pjsip_udp_transport_cfg_default(&pj_cfg, ipAddress.getFamily()); pj_cfg.bind_addr = ipAddress; pjsip_transport* transport = nullptr; if (pj_status_t status = pjsip_udp_transport_start2(endpt_, &pj_cfg, &transport)) { JAMI_ERR("pjsip_udp_transport_start2 failed with error %d: %s", status, sip_utils::sip_strerror(status).c_str()); JAMI_ERR("UDP IPv%s Transport did not start on %s", ipAddress.isIpv4() ? "4" : "6", ipAddress.toString(true).c_str()); return nullptr; } JAMI_DBG("Created UDP transport on address %s", ipAddress.toString(true).c_str()); return std::make_shared<SipTransport>(transport); } std::shared_ptr<TlsListener> SipTransportBroker::getTlsListener(const dhtnet::IpAddr& ipAddress, const pjsip_tls_setting* settings) { RETURN_IF_FAIL(settings, nullptr, "TLS settings not specified"); RETURN_IF_FAIL(ipAddress, nullptr, "Unable to determine IP address for this transport"); JAMI_DEBUG("Creating TLS listener on {:s}...", ipAddress.toString(true)); #if 0 JAMI_DBG(" ca_list_file : %s", settings->ca_list_file.ptr); JAMI_DBG(" cert_file : %s", settings->cert_file.ptr); JAMI_DBG(" ciphers_num : %d", settings->ciphers_num); JAMI_DBG(" verify server %d client %d client_cert %d", settings->verify_server, settings->verify_client, settings->require_client_cert); JAMI_DBG(" reuse_addr : %d", settings->reuse_addr); #endif pjsip_tpfactory* listener = nullptr; const pj_status_t status = pjsip_tls_transport_start2(endpt_, settings, ipAddress.pjPtr(), nullptr, 1, &listener); if (status != PJ_SUCCESS) { JAMI_ERR("TLS listener did not start: %s", sip_utils::sip_strerror(status).c_str()); return nullptr; } return std::make_shared<TlsListener>(listener); } std::shared_ptr<SipTransport> SipTransportBroker::getTlsTransport(const std::shared_ptr<TlsListener>& l, const dhtnet::IpAddr& remote, const std::string& remote_name) { if (!l || !remote) return nullptr; dhtnet::IpAddr remoteAddr {remote}; if (remoteAddr.getPort() == 0) remoteAddr.setPort(pjsip_transport_get_default_port_for_type(l->get()->type)); JAMI_DBG("Get new TLS transport to %s", remoteAddr.toString(true).c_str()); pjsip_tpselector sel; sel.type = PJSIP_TPSELECTOR_LISTENER; sel.u.listener = l->get(); sel.disable_connection_reuse = PJ_FALSE; pjsip_tx_data tx_data; tx_data.dest_info.name = pj_str_t {(char*) remote_name.data(), (pj_ssize_t) remote_name.size()}; pjsip_transport* transport = nullptr; pj_status_t status = pjsip_endpt_acquire_transport2(endpt_, l->get()->type, remoteAddr.pjPtr(), remoteAddr.getLength(), &sel, remote_name.empty() ? nullptr : &tx_data, &transport); if (!transport || status != PJ_SUCCESS) { JAMI_ERR("Unable to get new TLS transport: %s", sip_utils::sip_strerror(status).c_str()); return nullptr; } auto ret = std::make_shared<SipTransport>(transport, l); pjsip_transport_dec_ref(transport); { std::lock_guard lock(transportMapMutex_); transports_[ret->get()] = ret; } return ret; } std::shared_ptr<SipTransport> SipTransportBroker::getChanneledTransport(const std::shared_ptr<SIPAccountBase>& account, const std::shared_ptr<dhtnet::ChannelSocket>& socket, onShutdownCb&& cb) { if (!socket) return {}; auto sips_tr = std::make_unique<tls::ChanneledSIPTransport>(endpt_, socket, std::move(cb)); auto tr = sips_tr->getTransportBase(); auto sip_tr = std::make_shared<SipTransport>(tr, socket->peerCertificate()); sip_tr->setDeviceId(socket->deviceId().toString()); sip_tr->setAccount(account); { std::lock_guard lock(transportMapMutex_); // we do not check for key existence as we've just created it // (member of new SipIceTransport instance) transports_.emplace(tr, sip_tr); } sips_tr->start(); sips_tr.release(); // managed by PJSIP now return sip_tr; } } // namespace jami
14,729
C++
.cpp
369
30.97832
140
0.601091
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,833
pres_sub_client.cpp
savoirfairelinux_jami-daemon/src/sip/pres_sub_client.cpp
/* * Copyright (C) 2012, 2013 LOTES TM LLC * Author : Andrey Loukhnov <aol.nnov@gmail.com> * * This file is a part of pult5-voip * * pult5-voip is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * pult5-voip is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this programm. If not, see <http://www.gnu.org/licenses/>. */ #include <pj/log.h> #include <pj/rand.h> #include <pjsip/sip_module.h> #include <pjsip/sip_types.h> #include <pjsip/sip_event.h> #include <pjsip/sip_transaction.h> #include <pjsip/sip_dialog.h> #include <pjsip/sip_endpoint.h> #include <string> #include <sstream> #include <thread> #include <pj/pool.h> #include <pjsip/sip_ua_layer.h> #include <pjsip-simple/evsub.h> #include <unistd.h> #include "pres_sub_client.h" #include "sip/sipaccount.h" #include "sip/sippresence.h" #include "sip/sipvoiplink.h" #include "connectivity/sip_utils.h" #include "manager.h" #include "client/ring_signal.h" #include "logger.h" #define PRES_TIMER 300 // 5min namespace jami { using sip_utils::CONST_PJ_STR; int PresSubClient::modId_ = 0; // used to extract data structure from event_subscription void PresSubClient::pres_client_timer_cb(pj_timer_heap_t* /*th*/, pj_timer_entry* entry) { PresSubClient* c = (PresSubClient*) entry->user_data; JAMI_DBG("timeout for %.*s", (int)c->getURI().size(), c->getURI().data()); } /* Callback called when *client* subscription state has changed. */ void PresSubClient::pres_client_evsub_on_state(pjsip_evsub* sub, pjsip_event* event) { PJ_UNUSED_ARG(event); PresSubClient* pres_client = (PresSubClient*) pjsip_evsub_get_mod_data(sub, modId_); /* No need to pres->lock() here since the client has a locked dialog*/ if (!pres_client) { JAMI_WARN("pres_client not found"); return; } JAMI_DBG("Subscription for pres_client '%.*s' is '%s'", (int)pres_client->getURI().size(), pres_client->getURI().data(), pjsip_evsub_get_state_name(sub) ? pjsip_evsub_get_state_name(sub) : "null"); pjsip_evsub_state state = pjsip_evsub_get_state(sub); SIPPresence* pres = pres_client->getPresence(); if (state == PJSIP_EVSUB_STATE_ACCEPTED) { pres_client->enable(true); emitSignal<libjami::PresenceSignal::SubscriptionStateChanged>(pres->getAccount() ->getAccountID(), std::string(pres_client->getURI()), PJ_TRUE); pres->getAccount()->supportPresence(PRESENCE_FUNCTION_SUBSCRIBE, true); } else if (state == PJSIP_EVSUB_STATE_TERMINATED) { int resub_delay = -1; pj_strdup_with_null(pres_client->pool_, &pres_client->term_reason_, pjsip_evsub_get_termination_reason(sub)); emitSignal<libjami::PresenceSignal::SubscriptionStateChanged>(pres->getAccount() ->getAccountID(), std::string(pres_client->getURI()), PJ_FALSE); pres_client->term_code_ = 200; /* Determine whether to resubscribe automatically */ if (event && event->type == PJSIP_EVENT_TSX_STATE) { const pjsip_transaction* tsx = event->body.tsx_state.tsx; if (pjsip_method_cmp(&tsx->method, &pjsip_subscribe_method) == 0) { pres_client->term_code_ = tsx->status_code; std::ostringstream os; os << pres_client->term_code_; const std::string error = os.str() + "/" + sip_utils::as_view(pres_client->term_reason_); std::string msg; bool subscribe_allowed = PJ_FALSE; switch (tsx->status_code) { case PJSIP_SC_CALL_TSX_DOES_NOT_EXIST: /* 481: we refreshed too late? resubscribe * immediately. */ /* But this must only happen when the 481 is received * on subscription refresh request. We MUST NOT try to * resubscribe automatically if the 481 is received * on the initial SUBSCRIBE (if server returns this * response for some reason). */ if (pres_client->dlg_->remote.contact) resub_delay = 500; msg = "Bad subscribe refresh."; subscribe_allowed = PJ_TRUE; break; case PJSIP_SC_NOT_FOUND: msg = "Subscribe context not set for this buddy."; subscribe_allowed = PJ_TRUE; break; case PJSIP_SC_FORBIDDEN: msg = "Subscribe not allowed for this buddy."; subscribe_allowed = PJ_TRUE; break; case PJSIP_SC_PRECONDITION_FAILURE: msg = "Wrong server."; break; } /* report error: * 1) send a signal through DBus * 2) change the support field in the account schema if the pres_sub's server * is the same as the account's server */ emitSignal<libjami::PresenceSignal::ServerError>( pres_client->getPresence()->getAccount()->getAccountID(), error, msg); auto account_host = sip_utils::as_view(*pj_gethostname()); auto sub_host = sip_utils::getHostFromUri(pres_client->getURI()); if (not subscribe_allowed and account_host == sub_host) pres_client->getPresence() ->getAccount() ->supportPresence(PRESENCE_FUNCTION_SUBSCRIBE, false); } else if (pjsip_method_cmp(&tsx->method, &pjsip_notify_method) == 0) { if (pres_client->isTermReason("deactivated") || pres_client->isTermReason("timeout")) { /* deactivated: The subscription has been terminated, * but the subscriber SHOULD retry immediately with * a new subscription. */ /* timeout: The subscription has been terminated * because it was not refreshed before it expired. * Clients MAY re-subscribe immediately. The * "retry-after" parameter has no semantics for * "timeout". */ resub_delay = 500; } else if (pres_client->isTermReason("probation") || pres_client->isTermReason("giveup")) { /* probation: The subscription has been terminated, * but the client SHOULD retry at some later time. * If a "retry-after" parameter is also present, the * client SHOULD wait at least the number of seconds * specified by that parameter before attempting to re- * subscribe. */ /* giveup: The subscription has been terminated because * the notifier was unable to obtain authorization in a * timely fashion. If a "retry-after" parameter is * also present, the client SHOULD wait at least the * number of seconds specified by that parameter before * attempting to re-subscribe; otherwise, the client * MAY retry immediately, but will likely get put back * into pending state. */ const pjsip_sub_state_hdr* sub_hdr; constexpr pj_str_t sub_state = CONST_PJ_STR("Subscription-State"); const pjsip_msg* msg; msg = event->body.tsx_state.src.rdata->msg_info.msg; sub_hdr = (const pjsip_sub_state_hdr*) pjsip_msg_find_hdr_by_name(msg, &sub_state, NULL); if (sub_hdr && sub_hdr->retry_after > 0) resub_delay = sub_hdr->retry_after * 1000; } } } /* For other cases of subscription termination, if resubscribe * timer is not set, schedule with default expiration (plus minus * some random value, to avoid sending SUBSCRIBEs all at once) */ if (resub_delay == -1) { resub_delay = PRES_TIMER * 1000; } pres_client->sub_ = sub; pres_client->rescheduleTimer(PJ_TRUE, resub_delay); } else { // state==ACTIVE ...... // This will clear the last termination code/reason pres_client->term_code_ = 0; pres_client->term_reason_.ptr = NULL; } /* Clear subscription */ if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) { pjsip_evsub_terminate(pres_client->sub_, PJ_FALSE); // = NULL; pres_client->status_.info_cnt = 0; pres_client->dlg_ = NULL; pres_client->rescheduleTimer(PJ_FALSE, 0); pjsip_evsub_set_mod_data(sub, modId_, NULL); pres_client->enable(false); } } /* Callback when transaction state has changed. */ void PresSubClient::pres_client_evsub_on_tsx_state(pjsip_evsub* sub, pjsip_transaction* tsx, pjsip_event* event) { PresSubClient* pres_client; pjsip_contact_hdr* contact_hdr; pres_client = (PresSubClient*) pjsip_evsub_get_mod_data(sub, modId_); /* No need to pres->lock() here since the client has a locked dialog*/ if (!pres_client) { JAMI_WARN("Unable to find pres_client."); return; } /* We only use this to update pres_client's Contact, when it's not * set. */ if (pres_client->contact_.slen != 0) { /* Contact already set */ return; } /* Only care about 2xx response to outgoing SUBSCRIBE */ if (tsx->status_code / 100 != 2 || tsx->role != PJSIP_UAC_ROLE || event->type != PJSIP_EVENT_RX_MSG || pjsip_method_cmp(&tsx->method, pjsip_get_subscribe_method()) != 0) { return; } /* Find contact header. */ contact_hdr = (pjsip_contact_hdr*) pjsip_msg_find_hdr(event->body.rx_msg.rdata->msg_info.msg, PJSIP_H_CONTACT, NULL); if (!contact_hdr || !contact_hdr->uri) { return; } pres_client->contact_.ptr = (char*) pj_pool_alloc(pres_client->pool_, PJSIP_MAX_URL_SIZE); pres_client->contact_.slen = pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, contact_hdr->uri, pres_client->contact_.ptr, PJSIP_MAX_URL_SIZE); if (pres_client->contact_.slen < 0) pres_client->contact_.slen = 0; } /* Callback called when we receive NOTIFY */ void PresSubClient::pres_client_evsub_on_rx_notify(pjsip_evsub* sub, pjsip_rx_data* rdata, int* p_st_code, pj_str_t** p_st_text, pjsip_hdr* res_hdr, pjsip_msg_body** p_body) { PresSubClient* pres_client = (PresSubClient*) pjsip_evsub_get_mod_data(sub, modId_); if (!pres_client) { JAMI_WARN("Unable to find pres_client from ev_sub."); return; } /* No need to pres->lock() here since the client has a locked dialog*/ pjsip_pres_get_status(sub, &pres_client->status_); pres_client->reportPresence(); /* The default is to send 200 response to NOTIFY. * Just leave it there. */ PJ_UNUSED_ARG(rdata); PJ_UNUSED_ARG(p_st_code); PJ_UNUSED_ARG(p_st_text); PJ_UNUSED_ARG(res_hdr); PJ_UNUSED_ARG(p_body); } PresSubClient::PresSubClient(const std::string& uri, SIPPresence* pres) : pres_(pres) , uri_ {0, 0} , contact_ {0, 0} , display_() , dlg_(NULL) , monitored_(false) , name_() , cp_() , pool_(0) , status_() , sub_(NULL) , term_code_(0) , term_reason_() , timer_() , user_data_(NULL) , lock_count_(0) , lock_flag_(0) { pj_caching_pool_init(&cp_, &pj_pool_factory_default_policy, 0); pool_ = pj_pool_create(&cp_.factory, "Pres_sub_client", 512, 512, NULL); uri_ = pj_strdup3(pool_, uri.c_str()); contact_ = pj_strdup3(pool_, pres_->getAccount()->getFromUri().c_str()); } PresSubClient::~PresSubClient() { JAMI_DBG("Destroying pres_client object with uri %.*s", (int) uri_.slen, uri_.ptr); rescheduleTimer(PJ_FALSE, 0); unsubscribe(); pj_pool_release(pool_); } bool PresSubClient::isSubscribed() { return monitored_; } std::string_view PresSubClient::getURI() { return {uri_.ptr, (size_t)uri_.slen}; } SIPPresence* PresSubClient::getPresence() { return pres_; } bool PresSubClient::isPresent() { return status_.info[0].basic_open; } std::string_view PresSubClient::getLineStatus() { return {status_.info[0].rpid.note.ptr, (size_t)status_.info[0].rpid.note.slen}; } bool PresSubClient::isTermReason(const std::string& reason) { const std::string_view myReason(term_reason_.ptr, (size_t)term_reason_.slen); return not myReason.compare(reason); } void PresSubClient::rescheduleTimer(bool reschedule, unsigned msec) { if (timer_.id) { pjsip_endpt_cancel_timer(Manager::instance().sipVoIPLink().getEndpoint(), &timer_); timer_.id = PJ_FALSE; } if (reschedule) { pj_time_val delay; JAMI_WARN("pres_client %.*s will resubscribe in %u ms (reason: %.*s)", (int) uri_.slen, uri_.ptr, msec, (int) term_reason_.slen, term_reason_.ptr); pj_timer_entry_init(&timer_, 0, this, &pres_client_timer_cb); delay.sec = 0; delay.msec = msec; pj_time_val_normalize(&delay); if (pjsip_endpt_schedule_timer(Manager::instance().sipVoIPLink().getEndpoint(), &timer_, &delay) == PJ_SUCCESS) { timer_.id = PJ_TRUE; } } } void PresSubClient::enable(bool flag) { JAMI_DBG("pres_client %.*s is %s monitored.", (int)getURI().size(), getURI().data(), flag ? "" : "NOT"); if (flag and not monitored_) pres_->addPresSubClient(this); monitored_ = flag; } void PresSubClient::reportPresence() { /* callback*/ pres_->reportPresSubClientNotification(getURI(), &status_); } bool PresSubClient::lock() { unsigned i; for (i = 0; i < 50; i++) { if (not pres_->tryLock()) { // FIXME: i/10 in ms, sure!? std::this_thread::sleep_for(std::chrono::milliseconds(i / 10)); continue; } lock_flag_ = PRESENCE_LOCK_FLAG; if (dlg_ == NULL) { pres_->unlock(); return true; } if (pjsip_dlg_try_inc_lock(dlg_) != PJ_SUCCESS) { lock_flag_ = 0; pres_->unlock(); // FIXME: i/10 in ms, sure!? std::this_thread::sleep_for(std::chrono::milliseconds(i / 10)); continue; } lock_flag_ = PRESENCE_CLIENT_LOCK_FLAG; pres_->unlock(); } if (lock_flag_ == 0) { JAMI_DBG("pres_client failed to lock : timeout"); return false; } return true; } void PresSubClient::unlock() { if (lock_flag_ & PRESENCE_CLIENT_LOCK_FLAG) pjsip_dlg_dec_lock(dlg_); if (lock_flag_ & PRESENCE_LOCK_FLAG) pres_->unlock(); } bool PresSubClient::unsubscribe() { if (not lock()) return false; monitored_ = false; pjsip_tx_data* tdata; pj_status_t retStatus; if (sub_ == NULL or dlg_ == NULL) { JAMI_WARN("PresSubClient already unsubscribed."); unlock(); return false; } if (pjsip_evsub_get_state(sub_) == PJSIP_EVSUB_STATE_TERMINATED) { JAMI_WARN("pres_client already unsubscribed sub=TERMINATED."); sub_ = NULL; unlock(); return false; } /* Unsubscribe means send a subscribe with timeout=0s*/ JAMI_WARN("pres_client %.*s: unsubscribing..", (int) uri_.slen, uri_.ptr); retStatus = pjsip_pres_initiate(sub_, 0, &tdata); if (retStatus == PJ_SUCCESS) { pres_->fillDoc(tdata, NULL); retStatus = pjsip_pres_send_request(sub_, tdata); } if (retStatus != PJ_SUCCESS and sub_) { pjsip_pres_terminate(sub_, PJ_FALSE); sub_ = NULL; JAMI_WARN("Unable to unsubscribe presence (%d)", retStatus); unlock(); return false; } // pjsip_evsub_set_mod_data(sub_, modId_, NULL); // Not interested with further events unlock(); return true; } bool PresSubClient::subscribe() { if (sub_ and dlg_) { // do not bother if already subscribed pjsip_evsub_terminate(sub_, PJ_FALSE); JAMI_DBG("PreseSubClient %.*s: already subscribed. Refresh it.", (int) uri_.slen, uri_.ptr); } // subscribe pjsip_evsub_user pres_callback; pjsip_tx_data* tdata; pj_status_t status; /* Event subscription callback. */ pj_bzero(&pres_callback, sizeof(pres_callback)); pres_callback.on_evsub_state = &pres_client_evsub_on_state; pres_callback.on_tsx_state = &pres_client_evsub_on_tsx_state; pres_callback.on_rx_notify = &pres_client_evsub_on_rx_notify; SIPAccount* acc = pres_->getAccount(); JAMI_DBG("PresSubClient %.*s: subscribing ", (int) uri_.slen, uri_.ptr); /* Create UAC dialog */ pj_str_t from = pj_strdup3(pool_, acc->getFromUri().c_str()); status = pjsip_dlg_create_uac(pjsip_ua_instance(), &from, &contact_, &uri_, NULL, &dlg_); if (status != PJ_SUCCESS) { JAMI_ERR("Unable to create dialog \n"); return false; } /* Add credential for auth. */ if (acc->hasCredentials() and pjsip_auth_clt_set_credentials(&dlg_->auth_sess, acc->getCredentialCount(), acc->getCredInfo()) != PJ_SUCCESS) { JAMI_ERR("Unable to initialize credentials for subscribe session authentication"); } /* Increment the dialog's lock otherwise when presence session creation * fails the dialog will be destroyed prematurely. */ pjsip_dlg_inc_lock(dlg_); status = pjsip_pres_create_uac(dlg_, &pres_callback, PJSIP_EVSUB_NO_EVENT_ID, &sub_); if (status != PJ_SUCCESS) { sub_ = NULL; JAMI_WARN("Unable to create presence client (%d)", status); /* This should destroy the dialog since there's no session * referencing it */ if (dlg_) { pjsip_dlg_dec_lock(dlg_); } return false; } /* Add credential for authentication */ if (acc->hasCredentials() and pjsip_auth_clt_set_credentials(&dlg_->auth_sess, acc->getCredentialCount(), acc->getCredInfo()) != PJ_SUCCESS) { JAMI_ERR("Unable to initialize credentials for invite session authentication"); return false; } /* Set route-set */ pjsip_regc* regc = acc->getRegistrationInfo(); if (regc and acc->hasServiceRoute()) pjsip_regc_set_route_set(regc, sip_utils::createRouteSet(acc->getServiceRoute(), pres_->getPool())); // attach the client data to the sub pjsip_evsub_set_mod_data(sub_, modId_, this); status = pjsip_pres_initiate(sub_, -1, &tdata); if (status != PJ_SUCCESS) { if (dlg_) pjsip_dlg_dec_lock(dlg_); if (sub_) pjsip_pres_terminate(sub_, PJ_FALSE); sub_ = NULL; JAMI_WARN("Unable to create initial SUBSCRIBE (%d)", status); return false; } // pjsua_process_msg_data(tdata, NULL); status = pjsip_pres_send_request(sub_, tdata); if (status != PJ_SUCCESS) { if (dlg_) pjsip_dlg_dec_lock(dlg_); if (sub_) pjsip_pres_terminate(sub_, PJ_FALSE); sub_ = NULL; JAMI_WARN("Unable to send initial SUBSCRIBE (%d)", status); return false; } pjsip_dlg_dec_lock(dlg_); return true; } bool PresSubClient::match(PresSubClient* b) { return (b->getURI() == getURI()); } } // namespace jami
21,890
C++
.cpp
548
29.175182
108
0.55363
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,834
sipaccountbase_config.cpp
savoirfairelinux_jami-daemon/src/sip/sipaccountbase_config.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sipaccountbase_config.h" #include "account_const.h" #include "account_schema.h" #include "config/account_config_utils.h" namespace jami { namespace Conf { // SIP specific configuration keys const char* const BIND_ADDRESS_KEY = "bindAddress"; const char* const INTERFACE_KEY = "interface"; const char* const PORT_KEY = "port"; const char* const PUBLISH_ADDR_KEY = "publishAddr"; const char* const PUBLISH_PORT_KEY = "publishPort"; const char* const SAME_AS_LOCAL_KEY = "sameasLocal"; const char* const DTMF_TYPE_KEY = "dtmfType"; const char* const SERVICE_ROUTE_KEY = "serviceRoute"; const char* const ALLOW_IP_AUTO_REWRITE = "allowIPAutoRewrite"; const char* const PRESENCE_ENABLED_KEY = "presenceEnabled"; const char* const PRESENCE_PUBLISH_SUPPORTED_KEY = "presencePublishSupported"; const char* const PRESENCE_SUBSCRIBE_SUPPORTED_KEY = "presenceSubscribeSupported"; const char* const PRESENCE_STATUS_KEY = "presenceStatus"; const char* const PRESENCE_NOTE_KEY = "presenceNote"; const char* const STUN_ENABLED_KEY = "stunEnabled"; const char* const STUN_SERVER_KEY = "stunServer"; const char* const TURN_ENABLED_KEY = "turnEnabled"; const char* const TURN_SERVER_KEY = "turnServer"; const char* const TURN_SERVER_UNAME_KEY = "turnServerUserName"; const char* const TURN_SERVER_PWD_KEY = "turnServerPassword"; const char* const TURN_SERVER_REALM_KEY = "turnServerRealm"; const char* const CRED_KEY = "credential"; const char* const AUDIO_PORT_MIN_KEY = "audioPortMin"; const char* const AUDIO_PORT_MAX_KEY = "audioPortMax"; const char* const VIDEO_PORT_MIN_KEY = "videoPortMin"; const char* const VIDEO_PORT_MAX_KEY = "videoPortMax"; } // namespace Conf using yaml_utils::parseValueOptional; static void unserializeRange(const YAML::Node& node, const char* minKey, const char* maxKey, std::pair<uint16_t, uint16_t>& range) { int tmpMin = yaml_utils::parseValueOptional(node, minKey, tmpMin); int tmpMax = yaml_utils::parseValueOptional(node, maxKey, tmpMax); updateRange(tmpMin, tmpMax, range); } static void addRangeToDetails(std::map<std::string, std::string>& a, const char* minKey, const char* maxKey, const std::pair<uint16_t, uint16_t>& range) { a.emplace(minKey, std::to_string(range.first)); a.emplace(maxKey, std::to_string(range.second)); } void SipAccountBaseConfig::serializeDiff(YAML::Emitter& out, const SipAccountBaseConfig& DEFAULT_CONFIG) const { AccountConfig::serializeDiff(out, DEFAULT_CONFIG); SERIALIZE_CONFIG(Conf::DTMF_TYPE_KEY, dtmfType); SERIALIZE_CONFIG(Conf::INTERFACE_KEY, interface); SERIALIZE_CONFIG(Conf::PUBLISH_ADDR_KEY, publishedIp); SERIALIZE_CONFIG(Conf::SAME_AS_LOCAL_KEY, publishedSameasLocal); SERIALIZE_CONFIG(Conf::AUDIO_PORT_MAX_KEY, audioPortRange.second); SERIALIZE_CONFIG(Conf::AUDIO_PORT_MAX_KEY, audioPortRange.first); SERIALIZE_CONFIG(Conf::VIDEO_PORT_MAX_KEY, videoPortRange.second); SERIALIZE_CONFIG(Conf::VIDEO_PORT_MIN_KEY, videoPortRange.first); SERIALIZE_CONFIG(Conf::TURN_ENABLED_KEY, turnEnabled); SERIALIZE_CONFIG(Conf::TURN_SERVER_KEY, turnServer); SERIALIZE_CONFIG(Conf::TURN_SERVER_UNAME_KEY, turnServerUserName); SERIALIZE_CONFIG(Conf::TURN_SERVER_PWD_KEY, turnServerPwd); SERIALIZE_CONFIG(Conf::TURN_SERVER_REALM_KEY, turnServerRealm); } void SipAccountBaseConfig::unserialize(const YAML::Node& node) { AccountConfig::unserialize(node); parseValueOptional(node, Conf::INTERFACE_KEY, interface); parseValueOptional(node, Conf::SAME_AS_LOCAL_KEY, publishedSameasLocal); parseValueOptional(node, Conf::PUBLISH_ADDR_KEY, publishedIp); parseValueOptional(node, Conf::DTMF_TYPE_KEY, dtmfType); unserializeRange(node, Conf::AUDIO_PORT_MIN_KEY, Conf::AUDIO_PORT_MAX_KEY, audioPortRange); unserializeRange(node, Conf::VIDEO_PORT_MIN_KEY, Conf::VIDEO_PORT_MAX_KEY, videoPortRange); // ICE - STUN/TURN //parseValueOptional(node, Conf::STUN_ENABLED_KEY, stunEnabled); //parseValueOptional(node, Conf::STUN_SERVER_KEY, stunServer); parseValueOptional(node, Conf::TURN_ENABLED_KEY, turnEnabled); parseValueOptional(node, Conf::TURN_SERVER_KEY, turnServer); parseValueOptional(node, Conf::TURN_SERVER_UNAME_KEY, turnServerUserName); parseValueOptional(node, Conf::TURN_SERVER_PWD_KEY, turnServerPwd); parseValueOptional(node, Conf::TURN_SERVER_REALM_KEY, turnServerRealm); } std::map<std::string, std::string> SipAccountBaseConfig::toMap() const { auto a = AccountConfig::toMap(); addRangeToDetails(a, Conf::CONFIG_ACCOUNT_AUDIO_PORT_MIN, Conf::CONFIG_ACCOUNT_AUDIO_PORT_MAX, audioPortRange); addRangeToDetails(a, Conf::CONFIG_ACCOUNT_VIDEO_PORT_MIN, Conf::CONFIG_ACCOUNT_VIDEO_PORT_MAX, videoPortRange); a.emplace(Conf::CONFIG_ACCOUNT_DTMF_TYPE, dtmfType); a.emplace(Conf::CONFIG_LOCAL_INTERFACE, interface); a.emplace(Conf::CONFIG_PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_PUBLISHED_ADDRESS, publishedIp); a.emplace(Conf::CONFIG_TURN_ENABLE, turnEnabled ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TURN_SERVER, turnServer); a.emplace(Conf::CONFIG_TURN_SERVER_UNAME, turnServerUserName); a.emplace(Conf::CONFIG_TURN_SERVER_PWD, turnServerPwd); a.emplace(Conf::CONFIG_TURN_SERVER_REALM, turnServerRealm); return a; } void SipAccountBaseConfig::fromMap(const std::map<std::string, std::string>& details) { AccountConfig::fromMap(details); // general sip settings parseString(details, Conf::CONFIG_LOCAL_INTERFACE, interface); parseBool(details, Conf::CONFIG_PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal); parseString(details, Conf::CONFIG_PUBLISHED_ADDRESS, publishedIp); parseString(details, Conf::CONFIG_ACCOUNT_DTMF_TYPE, dtmfType); int tmpMin = -1; parseInt(details, Conf::CONFIG_ACCOUNT_AUDIO_PORT_MIN, tmpMin); int tmpMax = -1; parseInt(details, Conf::CONFIG_ACCOUNT_AUDIO_PORT_MAX, tmpMax); updateRange(tmpMin, tmpMax, audioPortRange); tmpMin = -1; parseInt(details, Conf::CONFIG_ACCOUNT_VIDEO_PORT_MIN, tmpMin); tmpMax = -1; parseInt(details, Conf::CONFIG_ACCOUNT_VIDEO_PORT_MAX, tmpMax); updateRange(tmpMin, tmpMax, videoPortRange); // ICE - STUN //parseBool(details, Conf::CONFIG_STUN_ENABLE, stunEnabled); //parseString(details, Conf::CONFIG_STUN_SERVER, stunServer); // ICE - TURN parseBool(details, Conf::CONFIG_TURN_ENABLE, turnEnabled); parseString(details, Conf::CONFIG_TURN_SERVER, turnServer); parseString(details, Conf::CONFIG_TURN_SERVER_UNAME, turnServerUserName); parseString(details, Conf::CONFIG_TURN_SERVER_PWD, turnServerPwd); parseString(details, Conf::CONFIG_TURN_SERVER_REALM, turnServerRealm); } }
7,701
C++
.cpp
160
43.64375
105
0.73601
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,835
sdes_negotiator.cpp
savoirfairelinux_jami-daemon/src/sip/sdes_negotiator.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sdes_negotiator.h" #include <iostream> #include <sstream> #include <algorithm> #include <stdexcept> #include <regex> #include <cstdio> namespace jami { std::vector<CryptoAttribute> SdesNegotiator::parse(const std::vector<std::string>& attributes) { // The patterns below try to follow // the ABNF grammar rules described in // RFC4568 section 9.2 with the general // syntax : // a=crypto:tag 1*WSP crypto-suite 1*WSP key-params *(1*WSP session-param) // used to match white space (which are used as separator) static const std::regex generalSyntaxPattern {"[\x20\x09]+"}; static const std::regex tagPattern {"^([0-9]{1,9})"}; static const std::regex cryptoSuitePattern {"(AES_CM_128_HMAC_SHA1_80|" "AES_CM_128_HMAC_SHA1_32|" "F8_128_HMAC_SHA1_80|" "[A-Za-z0-9_]+)"}; // srtp-crypto-suite-ext static const std::regex keyParamsPattern {"(inline|[A-Za-z0-9_]+)\\:" "([A-Za-z0-9\x2B\x2F\x3D]+)" "((\\|2\\^)([0-9]+)\\|" "([0-9]+)\\:" "([0-9]{1,3})\\;?)?"}; // Take each line from the vector // and parse its content std::vector<CryptoAttribute> cryptoAttributeVector; for (const auto& item : attributes) { // Split the line into its component that we will analyze further down. // Additional white space is added to better split the content // Result is stored in the sdsLine std::vector<std::string> sdesLine; std::smatch sm_generalSyntaxPattern; std::sregex_token_iterator iter(item.begin(), item.end(), generalSyntaxPattern, -1), end; for (; iter != end; ++iter) sdesLine.push_back(*iter); if (sdesLine.size() < 3) { throw ParseError("Missing components in SDES line"); } // Check if the attribute starts with a=crypto // and get the tag for this line std::string tag; std::smatch sm_tagPattern; if (std::regex_search(sdesLine.at(0), sm_tagPattern, tagPattern)) { tag = sm_tagPattern[1]; } else { throw ParseError("No Matching Found in Tag Attribute"); } // Check if the crypto suite is valid and retrieve // its value. std::string cryptoSuite; std::smatch sm_cryptoSuitePattern; if (std::regex_search(sdesLine.at(1), sm_cryptoSuitePattern, cryptoSuitePattern)) { cryptoSuite = sm_cryptoSuitePattern[1]; } else { throw ParseError("No Matching Found in CryptoSuite Attribute"); } // Parse one or more key-params field. // Group number is used to locate different paras std::string srtpKeyInfo; std::string srtpKeyMethod; std::string lifetime; std::string mkiLength; std::string mkiValue; std::smatch sm_keyParamsPattern; if (std::regex_search(sdesLine.at(2), sm_keyParamsPattern, keyParamsPattern)) { srtpKeyMethod = sm_keyParamsPattern[1]; srtpKeyInfo = sm_keyParamsPattern[2]; lifetime = sm_keyParamsPattern[5]; mkiValue = sm_keyParamsPattern[6]; mkiLength = sm_keyParamsPattern[7]; } else { throw ParseError("No Matching Found in Key-params Attribute"); } // Add the new CryptoAttribute to the vector cryptoAttributeVector.emplace_back(std::move(tag), std::move(cryptoSuite), std::move(srtpKeyMethod), std::move(srtpKeyInfo), std::move(lifetime), std::move(mkiValue), std::move(mkiLength)); } return cryptoAttributeVector; } CryptoAttribute SdesNegotiator::negotiate(const std::vector<std::string>& attributes) { try { auto cryptoAttributeVector(parse(attributes)); for (const auto& iter_offer : cryptoAttributeVector) { for (const auto& iter_local : CryptoSuites) { if (iter_offer.getCryptoSuite() == iter_local.name) return iter_offer; } } } catch (const ParseError& exception) { } return {}; } } // namespace jami
5,357
C++
.cpp
121
33.123967
97
0.582133
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
751,836
sipaccount.cpp
savoirfairelinux_jami-daemon/src/sip/sipaccount.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sip/sipaccount.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "compiler_intrinsics.h" #include "sdp.h" #include "sip/sipvoiplink.h" #include "sip/sipcall.h" #include "connectivity/sip_utils.h" #include "call_factory.h" #include "sip/sippresence.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <yaml-cpp/yaml.h> #pragma GCC diagnostic pop #include "account_schema.h" #include "config/yamlparser.h" #include "logger.h" #include "manager.h" #include "client/ring_signal.h" #include "jami/account_const.h" #ifdef ENABLE_VIDEO #include "libav_utils.h" #endif #include "system_codec_container.h" #include "string_utils.h" #include "im/instant_messaging.h" #include <dhtnet/ip_utils.h> #include <dhtnet/upnp/upnp_control.h> #include <opendht/crypto.h> #include <unistd.h> #include <algorithm> #include <array> #include <memory> #include <sstream> #include <cstdlib> #include <thread> #include <chrono> #include <ctime> #include <charconv> #ifdef _WIN32 #include <lmcons.h> #else #include <pwd.h> #endif namespace jami { using sip_utils::CONST_PJ_STR; static constexpr unsigned REGISTRATION_FIRST_RETRY_INTERVAL = 60; // seconds static constexpr unsigned REGISTRATION_RETRY_INTERVAL = 300; // seconds static constexpr std::string_view VALID_TLS_PROTOS[] = {"Default"sv, "TLSv1.2"sv, "TLSv1.1"sv, "TLSv1"sv}; static constexpr std::string_view PN_FCM = "fcm"sv; static constexpr std::string_view PN_APNS = "apns"sv; struct ctx { ctx(pjsip_auth_clt_sess* auth) : auth_sess(auth, &pjsip_auth_clt_deinit) {} std::weak_ptr<SIPAccount> acc; std::string to; uint64_t id; std::unique_ptr<pjsip_auth_clt_sess, decltype(&pjsip_auth_clt_deinit)> auth_sess; }; static void registration_cb(pjsip_regc_cbparam* param) { if (!param) { JAMI_ERR("registration callback parameter is null"); return; } auto account = static_cast<SIPAccount*>(param->token); if (!account) { JAMI_ERR("account doesn't exist in registration callback"); return; } account->onRegister(param); } SIPAccount::SIPAccount(const std::string& accountID, bool presenceEnabled) : SIPAccountBase(accountID) , ciphers_(100) , presence_(presenceEnabled ? new SIPPresence(this) : nullptr) { via_addr_.host.ptr = 0; via_addr_.host.slen = 0; via_addr_.port = 0; } SIPAccount::~SIPAccount() noexcept { // ensure that no registration callbacks survive past this point try { destroyRegistrationInfo(); setTransport(); } catch (...) { JAMI_ERR("Exception in SIPAccount destructor"); } delete presence_; } std::shared_ptr<SIPCall> SIPAccount::newIncomingCall(const std::string& from UNUSED, const std::vector<libjami::MediaMap>& mediaList, const std::shared_ptr<SipTransport>& transport) { auto call = Manager::instance().callFactory.newSipCall(shared(), Call::CallType::INCOMING, mediaList); call->setSipTransport(transport, getContactHeader()); return call; } std::shared_ptr<Call> SIPAccount::newOutgoingCall(std::string_view toUrl, const std::vector<libjami::MediaMap>& mediaList) { std::string to; int family; JAMI_DBG() << *this << "Calling SIP peer " << toUrl; auto& manager = Manager::instance(); std::shared_ptr<SIPCall> call; // SIP allows sending empty invites. if (not mediaList.empty() or isEmptyOffersEnabled()) { call = manager.callFactory.newSipCall(shared(), Call::CallType::OUTGOING, mediaList); } else { JAMI_WARN("Media list is empty, setting a default list"); call = manager.callFactory.newSipCall(shared(), Call::CallType::OUTGOING, MediaAttribute::mediaAttributesToMediaMaps( createDefaultMediaList(isVideoEnabled()))); } if (not call) throw std::runtime_error("Failed to create the call"); if (isIP2IP()) { bool ipv6 = dhtnet::IpAddr::isIpv6(toUrl); to = ipv6 ? dhtnet::IpAddr(toUrl).toString(false, true) : toUrl; family = ipv6 ? pj_AF_INET6() : pj_AF_INET(); // TODO: resolve remote host using SIPVoIPLink::resolveSrvName std::shared_ptr<SipTransport> t = isTlsEnabled() ? link_.sipTransportBroker->getTlsTransport(tlsListener_, dhtnet::IpAddr( sip_utils::getHostFromUri(to))) : transport_; setTransport(t); call->setSipTransport(t, getContactHeader()); JAMI_DBG("New %s IP to IP call to %s", ipv6 ? "IPv6" : "IPv4", to.c_str()); } else { to = toUrl; call->setSipTransport(transport_, getContactHeader()); // Use the same address family as the SIP transport family = pjsip_transport_type_get_af(getTransportType()); JAMI_DBG("UserAgent: New registered account call to %.*s", (int) toUrl.size(), toUrl.data()); } auto toUri = getToUri(to); // Do not init ICE yet if the media list is empty. This may occur // if we are sending an invite with no SDP offer. if (call->isIceEnabled() and not mediaList.empty()) { if (call->createIceMediaTransport(false)) { call->initIceMediaTransport(true); } } call->setPeerNumber(toUri); call->setPeerUri(toUri); const auto localAddress = dhtnet::ip_utils::getInterfaceAddr(getLocalInterface(), family); dhtnet::IpAddr addrSdp; if (getUPnPActive()) { /* use UPnP addr, or published addr if its set */ addrSdp = getPublishedSameasLocal() ? getUPnPIpAddress() : getPublishedIpAddress(); } else { addrSdp = isStunEnabled() or (not getPublishedSameasLocal()) ? getPublishedIpAddress() : localAddress; } /* fallback on local address */ if (not addrSdp) addrSdp = localAddress; // Building the local SDP offer auto& sdp = call->getSDP(); if (getPublishedSameasLocal()) sdp.setPublishedIP(addrSdp); else sdp.setPublishedIP(getPublishedAddress()); // TODO. We should not dot his here. Move it to SIPCall. const bool created = sdp.createOffer( MediaAttribute::buildMediaAttributesList(mediaList, isSrtpEnabled())); if (created) { std::weak_ptr<SIPCall> weak_call = call; manager.scheduler().run([this, weak_call] { if (auto call = weak_call.lock()) { if (not SIPStartCall(call)) { JAMI_ERR("Unable to send outgoing INVITE request for new call"); call->onFailure(); } } return false; }); } else { throw VoipLinkException("Unable to send outgoing INVITE request for new call"); } return call; } void SIPAccount::onTransportStateChanged(pjsip_transport_state state, const pjsip_transport_state_info* info) { pj_status_t currentStatus = transportStatus_; JAMI_DEBUG("Transport state changed to {:s} for account {:s}!", SipTransport::stateToStr(state), accountID_); if (!SipTransport::isAlive(state)) { if (info) { transportStatus_ = info->status; transportError_ = sip_utils::sip_strerror(info->status); JAMI_ERROR("Transport disconnected: {:s}", transportError_); } else { // This is already the generic error used by pjsip. transportStatus_ = PJSIP_SC_SERVICE_UNAVAILABLE; transportError_ = ""; } setRegistrationState(RegistrationState::ERROR_GENERIC, PJSIP_SC_TSX_TRANSPORT_ERROR); setTransport(); } else { // The status can be '0', this is the same as OK transportStatus_ = info && info->status ? info->status : PJSIP_SC_OK; transportError_ = ""; } // Notify the client of the new transport state if (currentStatus != transportStatus_) emitSignal<libjami::ConfigurationSignal::VolatileDetailsChanged>(accountID_, getVolatileAccountDetails()); } void SIPAccount::setTransport(const std::shared_ptr<SipTransport>& t) { if (t == transport_) return; if (transport_) { JAMI_DEBUG("Removing old transport [{}] from account", fmt::ptr(transport_.get())); // NOTE: do not call destroyRegistrationInfo() there as we must call the registration // callback if needed if (regc_) pjsip_regc_release_transport(regc_); transport_->removeStateListener(reinterpret_cast<uintptr_t>(this)); } transport_ = t; JAMI_DEBUG("Set new transport [{}]", fmt::ptr(transport_.get())); if (transport_) { transport_->addStateListener(reinterpret_cast<uintptr_t>(this), std::bind(&SIPAccount::onTransportStateChanged, this, std::placeholders::_1, std::placeholders::_2)); // Update contact address and header if (not initContactAddress()) { JAMI_DEBUG("Unable to register: invalid address"); return; } updateContactHeader(); } } pjsip_tpselector SIPAccount::getTransportSelector() { if (!transport_) return SIPVoIPLink::getTransportSelector(nullptr); return SIPVoIPLink::getTransportSelector(transport_->get()); } bool SIPAccount::SIPStartCall(std::shared_ptr<SIPCall>& call) { // Add Ice headers to local SDP if ice transport exist call->addLocalIceAttributes(); const std::string& toUri(call->getPeerNumber()); // expecting a fully well formed sip uri pj_str_t pjTo = sip_utils::CONST_PJ_STR(toUri); // Create the from header std::string from(getFromUri()); pj_str_t pjFrom = sip_utils::CONST_PJ_STR(from); auto transport = call->getTransport(); if (!transport) { JAMI_ERROR("Unable to start call without transport"); return false; } std::string contact = getContactHeader(); JAMI_DEBUG("contact header: {:s} / {:s} -> {:s}", contact, from, toUri); pj_str_t pjContact = sip_utils::CONST_PJ_STR(contact); auto local_sdp = isEmptyOffersEnabled() ? nullptr : call->getSDP().getLocalSdpSession(); pjsip_dialog* dialog {nullptr}; pjsip_inv_session* inv {nullptr}; if (!CreateClientDialogAndInvite(&pjFrom, &pjContact, &pjTo, nullptr, local_sdp, &dialog, &inv)) return false; inv->mod_data[link_.getModId()] = call.get(); call->setInviteSession(inv); updateDialogViaSentBy(dialog); if (hasServiceRoute()) pjsip_dlg_set_route_set(dialog, sip_utils::createRouteSet(getServiceRoute(), call->inviteSession_->pool)); if (hasCredentials() and pjsip_auth_clt_set_credentials(&dialog->auth_sess, getCredentialCount(), getCredInfo()) != PJ_SUCCESS) { JAMI_ERROR("Unable to initialize credentials for invite session authentication"); return false; } pjsip_tx_data* tdata; if (pjsip_inv_invite(call->inviteSession_.get(), &tdata) != PJ_SUCCESS) { JAMI_ERROR("Unable to initialize invite messager for this call"); return false; } const pjsip_tpselector tp_sel = link_.getTransportSelector(transport->get()); if (pjsip_dlg_set_transport(dialog, &tp_sel) != PJ_SUCCESS) { JAMI_ERROR("Unable to associate transport for invite session dialog"); return false; } // Add user-agent header sip_utils::addUserAgentHeader(getUserAgentName(), tdata); if (pjsip_inv_send_msg(call->inviteSession_.get(), tdata) != PJ_SUCCESS) { JAMI_ERROR("Unable to send invite message for this call"); return false; } call->setState(Call::CallState::ACTIVE, Call::ConnectionState::PROGRESSING); return true; } void SIPAccount::usePublishedAddressPortInVIA() { publishedIpStr_ = getPublishedIpAddress().toString(); via_addr_.host.ptr = (char*) publishedIpStr_.c_str(); via_addr_.host.slen = publishedIpStr_.size(); via_addr_.port = publishedPortUsed_; } void SIPAccount::useUPnPAddressPortInVIA() { upnpIpAddr_ = getUPnPIpAddress().toString(); via_addr_.host.ptr = (char*) upnpIpAddr_.c_str(); via_addr_.host.slen = upnpIpAddr_.size(); via_addr_.port = publishedPortUsed_; } template<typename T> static void validate(std::string& member, const std::string& param, const T& valid) { const auto begin = std::begin(valid); const auto end = std::end(valid); if (find(begin, end, param) != end) member = param; else JAMI_ERROR("Invalid parameter \"{:s}\"", param); } std::map<std::string, std::string> SIPAccount::getVolatileAccountDetails() const { auto a = SIPAccountBase::getVolatileAccountDetails(); a.emplace(Conf::CONFIG_ACCOUNT_REGISTRATION_STATE_CODE, std::to_string(registrationStateDetailed_.first)); a.emplace(Conf::CONFIG_ACCOUNT_REGISTRATION_STATE_DESC, registrationStateDetailed_.second); a.emplace(libjami::Account::VolatileProperties::InstantMessaging::OFF_CALL, TRUE_STR); if (presence_) { a.emplace(Conf::CONFIG_PRESENCE_STATUS, presence_->isOnline() ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_PRESENCE_NOTE, presence_->getNote()); } if (transport_ and transport_->isSecure() and transport_->isConnected()) { const auto& tlsInfos = transport_->getTlsInfos(); auto cipher = pj_ssl_cipher_name(tlsInfos.cipher); if (tlsInfos.cipher and not cipher) JAMI_WARN("Unknown cipher: %d", tlsInfos.cipher); a.emplace(libjami::TlsTransport::TLS_CIPHER, cipher ? cipher : ""); a.emplace(libjami::TlsTransport::TLS_PEER_CERT, tlsInfos.peerCert->toString()); auto ca = tlsInfos.peerCert->issuer; unsigned n = 0; while (ca) { std::ostringstream name_str; name_str << libjami::TlsTransport::TLS_PEER_CA_ << n++; a.emplace(name_str.str(), ca->toString()); ca = ca->issuer; } a.emplace(libjami::TlsTransport::TLS_PEER_CA_NUM, std::to_string(n)); } return a; } bool SIPAccount::mapPortUPnP() { dhtnet::upnp::Mapping map(dhtnet::upnp::PortType::UDP, config().publishedPort, config().localPort); map.setNotifyCallback([w = weak()](dhtnet::upnp::Mapping::sharedPtr_t mapRes) { if (auto accPtr = w.lock()) { auto oldPort = static_cast<in_port_t>(accPtr->publishedPortUsed_); bool success = mapRes->getState() == dhtnet::upnp::MappingState::OPEN or mapRes->getState() == dhtnet::upnp::MappingState::IN_PROGRESS; auto newPort = success ? mapRes->getExternalPort() : accPtr->config().publishedPort; if (not success and not accPtr->isRegistered()) { JAMI_WARNING( "[Account {:s}] Failed to open port {}: registering SIP account anyway", accPtr->getAccountID(), oldPort); accPtr->doRegister1_(); return; } if ((oldPort != newPort) or (accPtr->getRegistrationState() != RegistrationState::REGISTERED)) { if (not accPtr->isRegistered()) JAMI_WARNING("[Account {:s}] SIP port {} opened: registering SIP account", accPtr->getAccountID(), newPort); else JAMI_WARNING( "[Account {:s}] SIP port changed to {}: re-registering SIP account", accPtr->getAccountID(), newPort); accPtr->publishedPortUsed_ = newPort; } else { accPtr->connectivityChanged(); } accPtr->doRegister1_(); } }); auto mapRes = upnpCtrl_->reserveMapping(map); if (mapRes and mapRes->getState() == dhtnet::upnp::MappingState::OPEN) { return true; } return false; } bool SIPAccount::setPushNotificationToken(const std::string& pushDeviceToken) { JAMI_WARNING("[SIP Account {}] setPushNotificationToken: {}", getAccountID(), pushDeviceToken); if (SIPAccountBase::setPushNotificationToken(pushDeviceToken)) { if (config().enabled) doUnregister([&](bool /* transport_free */) { doRegister(); }); return true; } return false; } bool SIPAccount::setPushNotificationConfig(const std::map<std::string, std::string>& data) { if (SIPAccountBase::setPushNotificationConfig(data)) { if (config().enabled) doUnregister([&](bool /* transport_free */) { doRegister(); }); return true; } return false; } void SIPAccount::pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>&) { JAMI_WARNING("[SIP Account {:s}] pushNotificationReceived: {:s}", getAccountID(), from); if (config().enabled) doUnregister([&](bool /* transport_free */) { doRegister(); }); } void SIPAccount::doRegister() { if (not isUsable()) { JAMI_WARN("Account must be enabled and active to register, ignoring"); return; } JAMI_DEBUG("doRegister {:s}", config_->hostname); /* if UPnP is enabled, then wait for IGD to complete registration */ if (upnpCtrl_) { JAMI_DBG("UPnP: waiting for IGD to register SIP account"); setRegistrationState(RegistrationState::TRYING); if (not mapPortUPnP()) { JAMI_DBG("UPnP: UPNP request failed, try to register SIP account anyway"); doRegister1_(); } } else { doRegister1_(); } } void SIPAccount::doRegister1_() { { std::lock_guard lock(configurationMutex_); if (isIP2IP()) { doRegister2_(); return; } } link_.resolveSrvName(hasServiceRoute() ? getServiceRoute() : config().hostname, config().tlsEnable ? PJSIP_TRANSPORT_TLS : PJSIP_TRANSPORT_UDP, [w = weak()](std::vector<dhtnet::IpAddr> host_ips) { if (auto acc = w.lock()) { std::lock_guard lock( acc->configurationMutex_); if (host_ips.empty()) { JAMI_ERR("Unable to resolve hostname for registration."); acc->setRegistrationState(RegistrationState::ERROR_GENERIC, PJSIP_SC_NOT_FOUND); return; } acc->hostIp_ = host_ips[0]; acc->doRegister2_(); } }); } void SIPAccount::doRegister2_() { if (not isIP2IP() and not hostIp_) { setRegistrationState(RegistrationState::ERROR_GENERIC, PJSIP_SC_NOT_FOUND); JAMI_ERROR("Hostname not resolved."); return; } dhtnet::IpAddr bindAddress = createBindingAddress(); if (not bindAddress) { setRegistrationState(RegistrationState::ERROR_GENERIC, PJSIP_SC_NOT_FOUND); JAMI_ERROR("Unable to compute address to bind."); return; } bool ipv6 = bindAddress.isIpv6(); transportType_ = config().tlsEnable ? (ipv6 ? PJSIP_TRANSPORT_TLS6 : PJSIP_TRANSPORT_TLS) : (ipv6 ? PJSIP_TRANSPORT_UDP6 : PJSIP_TRANSPORT_UDP); // Init TLS settings if the user wants to use TLS if (config().tlsEnable) { JAMI_DEBUG("TLS is enabled for account {}", accountID_); // Dropping current calls already using the transport is currently required // with TLS. hangupCalls(); initTlsConfiguration(); if (!tlsListener_) { tlsListener_ = link_.sipTransportBroker->getTlsListener(bindAddress, getTlsSetting()); if (!tlsListener_) { setRegistrationState(RegistrationState::ERROR_GENERIC); JAMI_ERROR("Error creating TLS listener."); return; } } } else { tlsListener_.reset(); } // In our definition of the ip2ip profile (aka Direct IP Calls), // no registration should be performed if (isIP2IP()) { // If we use Tls for IP2IP, transports will be created on connection. if (!config().tlsEnable) { setTransport(link_.sipTransportBroker->getUdpTransport(bindAddress)); } setRegistrationState(RegistrationState::REGISTERED); return; } try { JAMI_WARNING("Creating transport"); transport_.reset(); if (isTlsEnabled()) { setTransport(link_.sipTransportBroker->getTlsTransport(tlsListener_, hostIp_, config().tlsServerName.empty() ? config().hostname : config().tlsServerName)); } else { setTransport(link_.sipTransportBroker->getUdpTransport(bindAddress)); } if (!transport_) throw VoipLinkException("Unable to create transport"); sendRegister(); } catch (const VoipLinkException& e) { JAMI_ERR("%s", e.what()); setRegistrationState(RegistrationState::ERROR_GENERIC); return; } if (presence_ and presence_->isEnabled()) { presence_->subscribeClient(getFromUri(), true); // self presence subscription presence_->sendPresence(true, ""); // try to publish whatever the status is. } } void SIPAccount::doUnregister(std::function<void(bool)> released_cb) { std::unique_lock<std::recursive_mutex> lock(configurationMutex_); tlsListener_.reset(); if (!isIP2IP()) { try { sendUnregister(); } catch (const VoipLinkException& e) { JAMI_ERR("doUnregister %s", e.what()); } } if (transport_) setTransport(); resetAutoRegistration(); lock.unlock(); if (released_cb) released_cb(not isIP2IP()); } void SIPAccount::connectivityChanged() { if (not isUsable()) { // nothing to do return; } doUnregister([acc = shared()](bool /* transport_free */) { if (acc->isUsable()) acc->doRegister(); }); } void SIPAccount::sendRegister() { if (not isUsable()) { JAMI_WARN("Account must be enabled and active to register, ignoring"); return; } bRegister_ = true; setRegistrationState(RegistrationState::TRYING); pjsip_regc* regc = nullptr; if (pjsip_regc_create(link_.getEndpoint(), (void*) this, &registration_cb, &regc) != PJ_SUCCESS) throw VoipLinkException("UserAgent: Unable to create regc structure."); std::string srvUri(getServerUri()); pj_str_t pjSrv {(char*) srvUri.data(), (pj_ssize_t) srvUri.size()}; // Generate the FROM header std::string from(getFromUri()); pj_str_t pjFrom(sip_utils::CONST_PJ_STR(from)); // Get the received header const std::string& received(getReceivedParameter()); std::string contact = getContactHeader(); JAMI_DBG("Using contact header %s in registration", contact.c_str()); if (transport_) { if (getUPnPActive() or not getPublishedSameasLocal() or (not received.empty() and received != getPublishedAddress())) { pjsip_host_port* via = getViaAddr(); JAMI_DBG("Setting VIA sent-by to %.*s:%d", (int) via->host.slen, via->host.ptr, via->port); if (pjsip_regc_set_via_sent_by(regc, via, transport_->get()) != PJ_SUCCESS) throw VoipLinkException("Unable to set the \"sent-by\" field"); } else if (isStunEnabled()) { if (pjsip_regc_set_via_sent_by(regc, getViaAddr(), transport_->get()) != PJ_SUCCESS) throw VoipLinkException("Unable to set the \"sent-by\" field"); } } pj_status_t status = PJ_SUCCESS; pj_str_t pjContact = sip_utils::CONST_PJ_STR(contact); if ((status = pjsip_regc_init(regc, &pjSrv, &pjFrom, &pjFrom, 1, &pjContact, getRegistrationExpire())) != PJ_SUCCESS) { JAMI_ERR("pjsip_regc_init failed with error %d: %s", status, sip_utils::sip_strerror(status).c_str()); throw VoipLinkException("Unable to initialize account registration structure"); } if (hasServiceRoute()) pjsip_regc_set_route_set(regc, sip_utils::createRouteSet(getServiceRoute(), link_.getPool())); pjsip_regc_set_credentials(regc, getCredentialCount(), getCredInfo()); pjsip_hdr hdr_list; pj_list_init(&hdr_list); auto pjUserAgent = CONST_PJ_STR(getUserAgentName()); constexpr pj_str_t STR_USER_AGENT = CONST_PJ_STR("User-Agent"); pjsip_generic_string_hdr* h = pjsip_generic_string_hdr_create(link_.getPool(), &STR_USER_AGENT, &pjUserAgent); pj_list_push_back(&hdr_list, (pjsip_hdr*) h); pjsip_regc_add_headers(regc, &hdr_list); pjsip_tx_data* tdata; if (pjsip_regc_register(regc, isRegistrationRefreshEnabled(), &tdata) != PJ_SUCCESS) throw VoipLinkException("Unable to initialize transaction data for account registration"); const pjsip_tpselector tp_sel = getTransportSelector(); if (pjsip_regc_set_transport(regc, &tp_sel) != PJ_SUCCESS) throw VoipLinkException("Unable to set transport"); if (tp_sel.u.transport) setUpTransmissionData(tdata, tp_sel.u.transport->key.type); // pjsip_regc_send increment the transport ref count by one, if ((status = pjsip_regc_send(regc, tdata)) != PJ_SUCCESS) { JAMI_ERR("pjsip_regc_send failed with error %d: %s", status, sip_utils::sip_strerror(status).c_str()); throw VoipLinkException("Unable to send account registration request"); } setRegistrationInfo(regc); } void SIPAccount::setUpTransmissionData(pjsip_tx_data* tdata, long transportKeyType) { if (hostIp_) { auto ai = &tdata->dest_info; ai->name = pj_strdup3(tdata->pool, config().hostname.c_str()); ai->addr.count = 1; ai->addr.entry[0].type = (pjsip_transport_type_e) transportKeyType; pj_memcpy(&ai->addr.entry[0].addr, hostIp_.pjPtr(), sizeof(pj_sockaddr)); ai->addr.entry[0].addr_len = hostIp_.getLength(); ai->cur_addr = 0; } } void SIPAccount::onRegister(pjsip_regc_cbparam* param) { if (param->regc != getRegistrationInfo()) return; if (param->status != PJ_SUCCESS) { JAMI_ERR("SIP registration error %d", param->status); destroyRegistrationInfo(); setRegistrationState(RegistrationState::ERROR_GENERIC, param->code); } else if (param->code < 0 || param->code >= 300) { JAMI_ERR("SIP registration failed, status=%d (%.*s)", param->code, (int) param->reason.slen, param->reason.ptr); destroyRegistrationInfo(); switch (param->code) { case PJSIP_SC_FORBIDDEN: setRegistrationState(RegistrationState::ERROR_AUTH, param->code); break; case PJSIP_SC_NOT_FOUND: setRegistrationState(RegistrationState::ERROR_HOST, param->code); break; case PJSIP_SC_REQUEST_TIMEOUT: setRegistrationState(RegistrationState::ERROR_HOST, param->code); break; case PJSIP_SC_SERVICE_UNAVAILABLE: setRegistrationState(RegistrationState::ERROR_SERVICE_UNAVAILABLE, param->code); break; default: setRegistrationState(RegistrationState::ERROR_GENERIC, param->code); } } else if (PJSIP_IS_STATUS_IN_CLASS(param->code, 200)) { // Update auto registration flag resetAutoRegistration(); if (param->expiration < 1) { destroyRegistrationInfo(); JAMI_DBG("Unregistration success"); setRegistrationState(RegistrationState::UNREGISTERED, param->code); } else { /* TODO Check and update SIP outbound status first, since the result * will determine if we should update re-registration */ // update_rfc5626_status(acc, param->rdata); if (config().allowIPAutoRewrite and checkNATAddress(param, link_.getPool())) JAMI_WARN("New contact: %s", getContactHeader().c_str()); /* TODO Check and update Service-Route header */ if (hasServiceRoute()) pjsip_regc_set_route_set(param->regc, sip_utils::createRouteSet(getServiceRoute(), link_.getPool())); setRegistrationState(RegistrationState::REGISTERED, param->code); } } /* Check if we need to auto retry registration. Basically, registration * failure codes triggering auto-retry are those of temporal failures * considered to be recoverable in relatively short term. */ switch (param->code) { case PJSIP_SC_REQUEST_TIMEOUT: case PJSIP_SC_INTERNAL_SERVER_ERROR: case PJSIP_SC_BAD_GATEWAY: case PJSIP_SC_SERVICE_UNAVAILABLE: case PJSIP_SC_SERVER_TIMEOUT: scheduleReregistration(); break; default: /* Global failure */ if (PJSIP_IS_STATUS_IN_CLASS(param->code, 600)) scheduleReregistration(); } if (param->expiration != config().registrationExpire) { JAMI_DBG("Registrar returned EXPIRE value [%u s] different from the requested [%u s]", param->expiration, config().registrationExpire); // NOTE: We don't alter the EXPIRE set by the user even if the registrar // returned a different value. PJSIP lib will set the proper timer for // the refresh, if the auto-regisration is enabled. } } void SIPAccount::sendUnregister() { // This may occurs if account failed to register and is in state INVALID if (!isRegistered()) { setRegistrationState(RegistrationState::UNREGISTERED); return; } bRegister_ = false; pjsip_regc* regc = getRegistrationInfo(); if (!regc) throw VoipLinkException("Registration structure is NULL"); pjsip_tx_data* tdata = nullptr; if (pjsip_regc_unregister(regc, &tdata) != PJ_SUCCESS) throw VoipLinkException("Unable to unregister sip account"); const pjsip_tpselector tp_sel = getTransportSelector(); if (pjsip_regc_set_transport(regc, &tp_sel) != PJ_SUCCESS) throw VoipLinkException("Unable to set transport"); if (tp_sel.u.transport) setUpTransmissionData(tdata, tp_sel.u.transport->key.type); pj_status_t status; if ((status = pjsip_regc_send(regc, tdata)) != PJ_SUCCESS) { JAMI_ERR("pjsip_regc_send failed with error %d: %s", status, sip_utils::sip_strerror(status).c_str()); throw VoipLinkException("Unable to send request to unregister sip account"); } } pj_uint32_t SIPAccount::tlsProtocolFromString(const std::string& method) { if (method == "Default") return PJSIP_SSL_DEFAULT_PROTO; if (method == "TLSv1.2") return PJ_SSL_SOCK_PROTO_TLS1_2; if (method == "TLSv1.1") return PJ_SSL_SOCK_PROTO_TLS1_2 | PJ_SSL_SOCK_PROTO_TLS1_1; if (method == "TLSv1") return PJ_SSL_SOCK_PROTO_TLS1_2 | PJ_SSL_SOCK_PROTO_TLS1_1 | PJ_SSL_SOCK_PROTO_TLS1; return PJSIP_SSL_DEFAULT_PROTO; } /** * PJSIP aborts if our cipher list exceeds 1000 characters */ void SIPAccount::trimCiphers() { size_t sum = 0; unsigned count = 0; static const size_t MAX_CIPHERS_STRLEN = 1000; for (const auto& item : ciphers_) { sum += strlen(pj_ssl_cipher_name(item)); if (sum > MAX_CIPHERS_STRLEN) break; ++count; } ciphers_.resize(count); } void SIPAccount::initTlsConfiguration() { pjsip_tls_setting_default(&tlsSetting_); const auto& conf = config(); tlsSetting_.proto = tlsProtocolFromString(conf.tlsMethod); // Determine the cipher list supported on this machine CipherArray avail_ciphers(256); unsigned cipherNum = avail_ciphers.size(); if (pj_ssl_cipher_get_availables(&avail_ciphers.front(), &cipherNum) != PJ_SUCCESS) JAMI_ERR("Unable to determine cipher list on this system"); avail_ciphers.resize(cipherNum); ciphers_.clear(); std::string_view stream(conf.tlsCiphers), item; while (jami::getline(stream, item, ' ')) { std::string cipher(item); auto item_cid = pj_ssl_cipher_id(cipher.c_str()); if (item_cid != PJ_TLS_UNKNOWN_CIPHER) { JAMI_WARN("Valid cipher: %s", cipher.c_str()); ciphers_.push_back(item_cid); } else JAMI_ERR("Invalid cipher: %s", cipher.c_str()); } ciphers_.erase(std::remove_if(ciphers_.begin(), ciphers_.end(), [&](pj_ssl_cipher c) { return std::find(avail_ciphers.cbegin(), avail_ciphers.cend(), c) == avail_ciphers.cend(); }), ciphers_.end()); trimCiphers(); tlsSetting_.ca_list_file = CONST_PJ_STR(conf.tlsCaListFile); tlsSetting_.cert_file = CONST_PJ_STR(conf.tlsCaListFile); tlsSetting_.privkey_file = CONST_PJ_STR(conf.tlsPrivateKeyFile); tlsSetting_.password = CONST_PJ_STR(conf.tlsPassword); JAMI_DBG("Using %zu ciphers", ciphers_.size()); tlsSetting_.ciphers_num = ciphers_.size(); if (tlsSetting_.ciphers_num > 0) { tlsSetting_.ciphers = &ciphers_.front(); } tlsSetting_.verify_server = conf.tlsVerifyServer; tlsSetting_.verify_client = conf.tlsVerifyClient; tlsSetting_.require_client_cert = conf.tlsRequireClientCertificate; pjsip_cfg()->endpt.disable_secure_dlg_check = conf.tlsDisableSecureDlgCheck; tlsSetting_.timeout.sec = conf.tlsNegotiationTimeout; tlsSetting_.qos_type = PJ_QOS_TYPE_BEST_EFFORT; tlsSetting_.qos_ignore_error = PJ_TRUE; } void SIPAccount::initStunConfiguration() { std::string_view stunServer(config().stunServer); auto pos = stunServer.find(':'); if (pos == std::string_view::npos) { stunServerName_ = sip_utils::CONST_PJ_STR(stunServer); stunPort_ = PJ_STUN_PORT; } else { stunServerName_ = sip_utils::CONST_PJ_STR(stunServer.substr(0, pos)); auto serverPort = stunServer.substr(pos + 1); stunPort_ = to_int<uint16_t>(serverPort); } } void SIPAccount::loadConfig() { SIPAccountBase::loadConfig(); setCredentials(config().credentials); enablePresence(config().presenceEnabled); initStunConfiguration(); if (config().tlsEnable) { initTlsConfiguration(); transportType_ = PJSIP_TRANSPORT_TLS; } else transportType_ = PJSIP_TRANSPORT_UDP; if (registrationState_ == RegistrationState::UNLOADED) setRegistrationState(RegistrationState::UNREGISTERED); } bool SIPAccount::fullMatch(std::string_view username, std::string_view hostname) const { return userMatch(username) and hostnameMatch(hostname); } bool SIPAccount::userMatch(std::string_view username) const { return !username.empty() and username == config().username; } bool SIPAccount::hostnameMatch(std::string_view hostname) const { if (hostname == config().hostname) return true; const auto a = dhtnet::ip_utils::getAddrList(hostname); const auto b = dhtnet::ip_utils::getAddrList(config().hostname); return dhtnet::ip_utils::haveCommonAddr(a, b); } bool SIPAccount::proxyMatch(std::string_view hostname) const { if (hostname == config().serviceRoute) return true; const auto a = dhtnet::ip_utils::getAddrList(hostname); const auto b = dhtnet::ip_utils::getAddrList(config().hostname); return dhtnet::ip_utils::haveCommonAddr(a, b); } std::string SIPAccount::getLoginName() { #ifndef _WIN32 struct passwd* user_info = getpwuid(getuid()); return user_info ? user_info->pw_name : ""; #else DWORD size = UNLEN + 1; TCHAR username[UNLEN + 1]; std::string uname; if (GetUserName((TCHAR*) username, &size)) { uname = jami::to_string(username); } return uname; #endif } std::string SIPAccount::getFromUri() const { std::string scheme; std::string transport; // Get login name if username is not specified const auto& conf = config(); std::string username(conf.username.empty() ? getLoginName() : conf.username); std::string hostname(conf.hostname); // UDP does not require the transport specification if (transportType_ == PJSIP_TRANSPORT_TLS || transportType_ == PJSIP_TRANSPORT_TLS6) { scheme = "sips:"; transport = ";transport=" + std::string(pjsip_transport_get_type_name(transportType_)); } else scheme = "sip:"; // Get machine hostname if not provided if (hostname.empty()) { hostname = sip_utils::as_view(*pj_gethostname()); } if (dhtnet::IpAddr::isIpv6(hostname)) hostname = dhtnet::IpAddr(hostname).toString(false, true); std::string uri = "<" + scheme + username + "@" + hostname + transport + ">"; if (not conf.displayName.empty()) return "\"" + conf.displayName + "\" " + uri; return uri; } std::string SIPAccount::getToUri(const std::string& username) const { std::string scheme; std::string transport; std::string hostname; // UDP does not require the transport specification if (transportType_ == PJSIP_TRANSPORT_TLS || transportType_ == PJSIP_TRANSPORT_TLS6) { scheme = "sips:"; transport = ";transport=" + std::string(pjsip_transport_get_type_name(transportType_)); } else scheme = "sip:"; // Check if scheme is already specified if (username.find("sip") != std::string::npos) scheme = ""; // Check if hostname is already specified if (username.find('@') == std::string::npos) hostname = config().hostname; if (not hostname.empty() and dhtnet::IpAddr::isIpv6(hostname)) hostname = dhtnet::IpAddr(hostname).toString(false, true); auto ltSymbol = username.find('<') == std::string::npos ? "<" : ""; auto gtSymbol = username.find('>') == std::string::npos ? ">" : ""; return ltSymbol + scheme + username + (hostname.empty() ? "" : "@") + hostname + transport + gtSymbol; } std::string SIPAccount::getServerUri() const { std::string scheme; std::string transport; // UDP does not require the transport specification if (transportType_ == PJSIP_TRANSPORT_TLS || transportType_ == PJSIP_TRANSPORT_TLS6) { scheme = "sips:"; transport = ";transport=" + std::string(pjsip_transport_get_type_name(transportType_)); } else { scheme = "sip:"; } std::string host; if (dhtnet::IpAddr::isIpv6(config().hostname)) host = dhtnet::IpAddr(config().hostname).toString(false, true); else host = config().hostname; return "<" + scheme + host + transport + ">"; } dhtnet::IpAddr SIPAccount::getContactAddress() const { std::lock_guard lock(contactMutex_); return contactAddress_; } std::string SIPAccount::getContactHeader() const { std::lock_guard lock(contactMutex_); return contactHeader_; } void SIPAccount::updateContactHeader() { std::lock_guard lock(contactMutex_); if (not transport_ or not transport_->get()) { JAMI_ERR("Transport not created yet"); return; } if (not contactAddress_) { JAMI_ERR("Invalid contact address: %s", contactAddress_.toString(true).c_str()); return; } auto contactHdr = printContactHeader(config().username, config().displayName, contactAddress_.toString(false, true), contactAddress_.getPort(), PJSIP_TRANSPORT_IS_SECURE(transport_->get()), config().deviceKey); contactHeader_ = std::move(contactHdr); } bool SIPAccount::initContactAddress() { // This method tries to determine the address to be used in the // contact header using the available information (current transport, // UPNP, STUN, ...). The contact address may be updated after the // registration using information sent by the registrar in the SIP // messages (see checkNATAddress). if (not transport_ or not transport_->get()) { JAMI_ERR("Transport not created yet"); return {}; } // The transport type must be specified, in our case START_OTHER refers to stun transport pjsip_transport_type_e transportType = transportType_; if (transportType == PJSIP_TRANSPORT_START_OTHER) transportType = PJSIP_TRANSPORT_UDP; std::string address; pj_uint16_t port; // Init the address to the local address. link_.findLocalAddressFromTransport(transport_->get(), transportType, config().hostname, address, port); if (getUPnPActive() and getUPnPIpAddress()) { address = getUPnPIpAddress().toString(); port = publishedPortUsed_; useUPnPAddressPortInVIA(); JAMI_DBG("Using UPnP address %s and port %d", address.c_str(), port); } else if (not config().publishedSameasLocal) { address = getPublishedIpAddress().toString(); port = config().publishedPort; JAMI_DBG("Using published address %s and port %d", address.c_str(), port); } else if (config().stunEnabled) { auto success = link_.findLocalAddressFromSTUN(transport_->get(), &stunServerName_, stunPort_, address, port); if (not success) emitSignal<libjami::ConfigurationSignal::StunStatusFailed>(getAccountID()); setPublishedAddress({address}); publishedPortUsed_ = port; usePublishedAddressPortInVIA(); } else { if (!receivedParameter_.empty()) { address = receivedParameter_; JAMI_DBG("Using received address %s", address.c_str()); } if (rPort_ > 0) { port = rPort_; JAMI_DBG("Using received port %d", port); } } std::lock_guard lock(contactMutex_); contactAddress_ = dhtnet::IpAddr(address); contactAddress_.setPort(port); return contactAddress_; } std::string SIPAccount::printContactHeader(const std::string& username, const std::string& displayName, const std::string& address, pj_uint16_t port, bool secure, const std::string& deviceKey) { // This method generates SIP contact header field, with push // notification parameters if any. // Example without push notification: // John Doe<sips:jdoe@10.10.10.10:5060;transport=tls> // Example with push notification: // John Doe<sips:jdoe@10.10.10.10:5060;transport=tls;pn-provider=XXX;pn-param=YYY;pn-prid=ZZZ> std::string quotedDisplayName = displayName.empty() ? "" : "\"" + displayName + "\" "; std::ostringstream contact; auto scheme = secure ? "sips" : "sip"; auto transport = secure ? ";transport=tls" : ""; contact << quotedDisplayName << "<" << scheme << ":" << username << (username.empty() ? "" : "@") << address << ":" << port << transport; if (not deviceKey.empty()) { contact #if defined(__ANDROID__) << ";pn-provider=" << PN_FCM #elif defined(__Apple__) << ";pn-provider=" << PN_APNS #endif << ";pn-param=" << ";pn-prid=" << deviceKey; } contact << ">"; return contact.str(); } pjsip_host_port SIPAccount::getHostPortFromSTUN(pj_pool_t* pool) { std::string addr; pj_uint16_t port; auto success = link_.findLocalAddressFromSTUN(transport_ ? transport_->get() : nullptr, &stunServerName_, stunPort_, addr, port); if (not success) emitSignal<libjami::ConfigurationSignal::StunStatusFailed>(getAccountID()); pjsip_host_port result; pj_strdup2(pool, &result.host, addr.c_str()); result.port = port; return result; } const std::vector<std::string>& SIPAccount::getSupportedTlsCiphers() { // Currently, both OpenSSL and GNUTLS implementations are static // reloading this for each account is unnecessary static std::vector<std::string> availCiphers {}; // LIMITATION Assume the size might change, if there aren't any ciphers, // this will cause the cache to be repopulated at each call for nothing. if (availCiphers.empty()) { unsigned cipherNum = 256; CipherArray avail_ciphers(cipherNum); if (pj_ssl_cipher_get_availables(&avail_ciphers.front(), &cipherNum) != PJ_SUCCESS) JAMI_ERR("Unable to determine cipher list on this system"); avail_ciphers.resize(cipherNum); availCiphers.reserve(cipherNum); for (const auto& item : avail_ciphers) { if (item > 0) // 0 doesn't have a name availCiphers.push_back(pj_ssl_cipher_name(item)); } } return availCiphers; } const std::vector<std::string>& SIPAccount::getSupportedTlsProtocols() { static std::vector<std::string> availProtos {VALID_TLS_PROTOS, VALID_TLS_PROTOS + std::size(VALID_TLS_PROTOS)}; return availProtos; } void SIPAccount::setCredentials(const std::vector<SipAccountConfig::Credentials>& creds) { cred_.clear(); cred_.reserve(creds.size()); bool md5HashingEnabled = Manager::instance().preferences.getMd5Hash(); for (auto& c : creds) { cred_.emplace_back( pjsip_cred_info {/*.realm = */ CONST_PJ_STR(c.realm), /*.scheme = */ CONST_PJ_STR("digest"), /*.username = */ CONST_PJ_STR(c.username), /*.data_type = */ (md5HashingEnabled ? PJSIP_CRED_DATA_DIGEST : PJSIP_CRED_DATA_PLAIN_PASSWD), /*.data = */ CONST_PJ_STR(md5HashingEnabled ? c.password_h : c.password), /*.ext = */ {}}); } } void SIPAccount::setRegistrationState(RegistrationState state, int details_code, const std::string& /*detail_str*/) { std::string details_str; const pj_str_t* description = pjsip_get_status_text(details_code); if (description) details_str = sip_utils::as_view(*description); registrationStateDetailed_ = {details_code, details_str}; SIPAccountBase::setRegistrationState(state, details_code, details_str); } bool SIPAccount::isIP2IP() const { return config().hostname.empty(); } SIPPresence* SIPAccount::getPresence() const { return presence_; } /** * Enable the presence module */ void SIPAccount::enablePresence(const bool& enabled) { if (!presence_) { JAMI_ERR("Presence not initialized"); return; } JAMI_DBG("Presence enabled for %s : %s.", accountID_.c_str(), enabled ? TRUE_STR : FALSE_STR); presence_->enable(enabled); } /** * Set the presence (PUBLISH/SUBSCRIBE) support flags * and process the change. */ void SIPAccount::supportPresence(int function, bool enabled) { if (!presence_) { JAMI_ERR("Presence not initialized"); return; } if (presence_->isSupported(function) == enabled) return; JAMI_DBG("Presence support for %s (%s: %s).", accountID_.c_str(), function == PRESENCE_FUNCTION_PUBLISH ? "publish" : "subscribe", enabled ? TRUE_STR : FALSE_STR); presence_->support(function, enabled); // force presence to disable when nothing is supported if (not presence_->isSupported(PRESENCE_FUNCTION_PUBLISH) and not presence_->isSupported(PRESENCE_FUNCTION_SUBSCRIBE)) enablePresence(false); Manager::instance().saveConfig(); // FIXME: bad signal used here, we need a global config changed signal. emitSignal<libjami::ConfigurationSignal::AccountsChanged>(); } MatchRank SIPAccount::matches(std::string_view userName, std::string_view server) const { if (fullMatch(userName, server)) { JAMI_DBG("Matching account id in request is a fullmatch %.*s@%.*s", (int) userName.size(), userName.data(), (int) server.size(), server.data()); return MatchRank::FULL; } else if (hostnameMatch(server)) { JAMI_DBG("Matching account id in request with hostname %.*s", (int) server.size(), server.data()); return MatchRank::PARTIAL; } else if (userMatch(userName)) { JAMI_DBG("Matching account id in request with username %.*s", (int) userName.size(), userName.data()); return MatchRank::PARTIAL; } else if (proxyMatch(server)) { JAMI_DBG("Matching account id in request with proxy %.*s", (int) server.size(), server.data()); return MatchRank::PARTIAL; } else { return MatchRank::NONE; } } void SIPAccount::destroyRegistrationInfo() { if (!regc_) return; pjsip_regc_destroy(regc_); regc_ = nullptr; } void SIPAccount::resetAutoRegistration() { auto_rereg_.active = PJ_FALSE; auto_rereg_.attempt_cnt = 0; if (auto_rereg_.timer.user_data) { delete ((std::weak_ptr<SIPAccount>*) auto_rereg_.timer.user_data); auto_rereg_.timer.user_data = nullptr; } } bool SIPAccount::checkNATAddress(pjsip_regc_cbparam* param, pj_pool_t* pool) { JAMI_DBG("[Account %s] Checking IP route after the registration", accountID_.c_str()); pjsip_transport* tp = param->rdata->tp_info.transport; /* Get the received and rport info */ pjsip_via_hdr* via = param->rdata->msg_info.via; int rport = 0; if (via->rport_param < 1) { /* Remote doesn't support rport */ rport = via->sent_by.port; if (rport == 0) { pjsip_transport_type_e tp_type; tp_type = (pjsip_transport_type_e) tp->key.type; rport = pjsip_transport_get_default_port_for_type(tp_type); } } else { rport = via->rport_param; } const pj_str_t* via_addr = via->recvd_param.slen != 0 ? &via->recvd_param : &via->sent_by.host; std::string via_addrstr(sip_utils::as_view(*via_addr)); /* Enclose IPv6 address in square brackets */ if (dhtnet::IpAddr::isIpv6(via_addrstr)) via_addrstr = dhtnet::IpAddr(via_addrstr).toString(false, true); JAMI_DBG("Checking received VIA address: %s", via_addrstr.c_str()); if (via_addr_.host.slen == 0 or via_tp_ != tp) { if (pj_strcmp(&via_addr_.host, via_addr)) pj_strdup(pool, &via_addr_.host, via_addr); // Update Via header via_addr_.port = rport; via_tp_ = tp; pjsip_regc_set_via_sent_by(regc_, &via_addr_, via_tp_); } // Set published Ip address setPublishedAddress(dhtnet::IpAddr(via_addrstr)); /* Compare received and rport with the URI in our registration */ dhtnet::IpAddr contact_addr = getContactAddress(); // TODO. Why note save the port in contact uri/header? if (contact_addr.getPort() == 0) { pjsip_transport_type_e tp_type; tp_type = (pjsip_transport_type_e) tp->key.type; contact_addr.setPort(pjsip_transport_get_default_port_for_type(tp_type)); } /* Convert IP address strings into sockaddr for comparison. * (http://trac.pjsip.org/repos/ticket/863) */ bool matched = false; dhtnet::IpAddr recv_addr {}; auto status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, via_addr, recv_addr.pjPtr()); recv_addr.setPort(rport); if (status == PJ_SUCCESS) { // Compare the addresses as sockaddr according to the ticket above matched = contact_addr == recv_addr; } else { // Compare the addresses as string, as before auto pjContactAddr = sip_utils::CONST_PJ_STR(contact_addr.toString()); matched = (contact_addr.getPort() == rport and pj_stricmp(&pjContactAddr, via_addr) == 0); } if (matched) { // Address doesn't change return false; } /* Get server IP */ dhtnet::IpAddr srv_ip = {std::string_view(param->rdata->pkt_info.src_name)}; /* At this point we've detected that the address as seen by registrar. * has changed. */ /* Do not switch if both Contact and server's IP address are * public but response contains private IP. A NAT in the middle * might have messed up with the SIP packets. See: * http://trac.pjsip.org/repos/ticket/643 * * This exception can be disabled by setting allow_contact_rewrite * to 2. In this case, the switch will always be done whenever there * is difference in the IP address in the response. */ if (not contact_addr.isPrivate() and not srv_ip.isPrivate() and recv_addr.isPrivate()) { /* Don't switch */ return false; } /* Also don't switch if only the port number part is different, and * the Via received address is private. * See http://trac.pjsip.org/repos/ticket/864 */ if (contact_addr == recv_addr and recv_addr.isPrivate()) { /* Don't switch */ return false; } JAMI_WARN("[account %s] Contact address changed: " "(%s --> %s:%d). Updating registration.", accountID_.c_str(), contact_addr.toString(true).c_str(), via_addrstr.data(), rport); /* * Build new Contact header */ { auto tempContact = printContactHeader(config().username, config().displayName, via_addrstr, rport, PJSIP_TRANSPORT_IS_SECURE(tp), config().deviceKey); if (tempContact.empty()) { JAMI_ERR("Invalid contact header"); return false; } // Update std::lock_guard lock(contactMutex_); contactHeader_ = std::move(tempContact); } if (regc_ != nullptr) { auto contactHdr = getContactHeader(); auto pjContact = sip_utils::CONST_PJ_STR(contactHdr); pjsip_regc_update_contact(regc_, 1, &pjContact); /* Perform new registration at the next registration cycle */ } return true; } /* Auto re-registration timeout callback */ void SIPAccount::autoReregTimerCb() { /* Check if the re-registration timer is still valid, e.g: while waiting * timeout timer application might have deleted the account or disabled * the auto-reregistration. */ if (not auto_rereg_.active) return; /* Start re-registration */ ++auto_rereg_.attempt_cnt; try { // If attempt_count was 0, we should call doRegister to reset transports if needed. if (auto_rereg_.attempt_cnt == 1) doRegister(); else sendRegister(); } catch (const VoipLinkException& e) { JAMI_ERR("Exception during SIP registration: %s", e.what()); scheduleReregistration(); } } /* Schedule reregistration for specified account. Note that the first * re-registration after a registration failure will be done immediately. * Also note that this function should be called within PJSUA mutex. */ void SIPAccount::scheduleReregistration() { if (!isUsable()) return; /* Cancel any re-registration timer */ if (auto_rereg_.timer.id) { auto_rereg_.timer.id = PJ_FALSE; pjsip_endpt_cancel_timer(link_.getEndpoint(), &auto_rereg_.timer); } /* Update re-registration flag */ auto_rereg_.active = PJ_TRUE; /* Set up timer for reregistration */ auto_rereg_.timer.cb = [](pj_timer_heap_t* /*th*/, pj_timer_entry* te) { if (auto sipAccount = static_cast<std::weak_ptr<SIPAccount>*>(te->user_data)->lock()) sipAccount->autoReregTimerCb(); }; if (not auto_rereg_.timer.user_data) auto_rereg_.timer.user_data = new std::weak_ptr<SIPAccount>(weak()); /* Reregistration attempt. The first attempt will be done sooner */ pj_time_val delay; delay.sec = auto_rereg_.attempt_cnt ? REGISTRATION_RETRY_INTERVAL : REGISTRATION_FIRST_RETRY_INTERVAL; delay.msec = 0; /* Randomize interval by +/- 10 secs */ if (delay.sec >= 10) { delay.msec = delay10ZeroDist_(rand); } else { delay.sec = 0; delay.msec = delay10PosDist_(rand); } pj_time_val_normalize(&delay); JAMI_WARNING("Scheduling re-registration retry in {:d} seconds..", delay.sec); auto_rereg_.timer.id = PJ_TRUE; if (pjsip_endpt_schedule_timer(link_.getEndpoint(), &auto_rereg_.timer, &delay) != PJ_SUCCESS) auto_rereg_.timer.id = PJ_FALSE; } void SIPAccount::updateDialogViaSentBy(pjsip_dialog* dlg) { if (config().allowIPAutoRewrite && via_addr_.host.slen > 0) pjsip_dlg_set_via_sent_by(dlg, &via_addr_, via_tp_); } #if 0 /** * Create Accept header for MESSAGE. */ static pjsip_accept_hdr* im_create_accept(pj_pool_t *pool) { /* Create Accept header. */ pjsip_accept_hdr *accept; accept = pjsip_accept_hdr_create(pool); accept->values[0] = CONST_PJ_STR("text/plain"); accept->values[1] = CONST_PJ_STR("application/im-iscomposing+xml"); accept->count = 2; return accept; } #endif void SIPAccount::sendMessage(const std::string& to, const std::string&, const std::map<std::string, std::string>& payloads, uint64_t id, bool, bool) { if (to.empty() or payloads.empty()) { JAMI_WARN("No sender or payload"); messageEngine_.onMessageSent(to, id, false); return; } auto toUri = getToUri(to); constexpr pjsip_method msg_method = {PJSIP_OTHER_METHOD, CONST_PJ_STR(sip_utils::SIP_METHODS::MESSAGE)}; std::string from(getFromUri()); pj_str_t pjFrom = sip_utils::CONST_PJ_STR(from); pj_str_t pjTo = sip_utils::CONST_PJ_STR(toUri); /* Create request. */ pjsip_tx_data* tdata; pj_status_t status = pjsip_endpt_create_request(link_.getEndpoint(), &msg_method, &pjTo, &pjFrom, &pjTo, nullptr, nullptr, -1, nullptr, &tdata); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to create request: {:s}", sip_utils::sip_strerror(status)); messageEngine_.onMessageSent(to, id, false); return; } /* Add Date Header. */ pj_str_t date_str; constexpr auto key = CONST_PJ_STR("Date"); pjsip_hdr* hdr; auto time = std::time(nullptr); auto date = std::ctime(&time); // the erase-remove idiom for a cstring, removes _all_ new lines with in date *std::remove(date, date + strlen(date), '\n') = '\0'; // Add Header hdr = reinterpret_cast<pjsip_hdr*>( pjsip_date_hdr_create(tdata->pool, &key, pj_cstr(&date_str, date))); pjsip_msg_add_hdr(tdata->msg, hdr); // Add user-agent header sip_utils::addUserAgentHeader(getUserAgentName(), tdata); // Set input token into callback std::unique_ptr<ctx> t {new ctx(new pjsip_auth_clt_sess)}; t->acc = shared(); t->to = to; t->id = id; /* Initialize Auth header. */ status = pjsip_auth_clt_init(t->auth_sess.get(), link_.getEndpoint(), tdata->pool, 0); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to initialize auth session: {:s}", sip_utils::sip_strerror(status)); messageEngine_.onMessageSent(to, id, false); return; } status = pjsip_auth_clt_set_credentials(t->auth_sess.get(), getCredentialCount(), getCredInfo()); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to set auth session data: {:s}", sip_utils::sip_strerror(status)); messageEngine_.onMessageSent(to, id, false); return; } const pjsip_tpselector tp_sel = getTransportSelector(); status = pjsip_tx_data_set_transport(tdata, &tp_sel); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to set transport: {:s}", sip_utils::sip_strerror(status)); messageEngine_.onMessageSent(to, id, false); return; } im::fillPJSIPMessageBody(*tdata, payloads); // Send message request with callback SendMessageOnComplete status = pjsip_endpt_send_request(link_.getEndpoint(), tdata, -1, t.release(), &onComplete); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to send request: {:s}", sip_utils::sip_strerror(status)); messageEngine_.onMessageSent(to, id, false); return; } } void SIPAccount::onComplete(void* token, pjsip_event* event) { std::unique_ptr<ctx> c {(ctx*) token}; int code; pj_status_t status; pj_assert(event->type == PJSIP_EVENT_TSX_STATE); code = event->body.tsx_state.tsx->status_code; auto acc = c->acc.lock(); if (not acc) return; // Check if Authorization Header if needed (request rejected by server) if (code == PJSIP_SC_UNAUTHORIZED || code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED) { JAMI_INFO("Authorization needed for SMS message - Resending"); pjsip_tx_data* new_request; // Add Authorization Header into msg status = pjsip_auth_clt_reinit_req(c->auth_sess.get(), event->body.tsx_state.src.rdata, event->body.tsx_state.tsx->last_tx, &new_request); if (status == PJ_SUCCESS) { // Increment Cseq number by one manually pjsip_cseq_hdr* cseq_hdr; cseq_hdr = (pjsip_cseq_hdr*) pjsip_msg_find_hdr(new_request->msg, PJSIP_H_CSEQ, NULL); cseq_hdr->cseq += 1; // Resend request auto to = c->to; auto id = c->id; status = pjsip_endpt_send_request(acc->link_.getEndpoint(), new_request, -1, c.release(), &onComplete); if (status != PJ_SUCCESS) { JAMI_ERROR("Unable to send request: {:s}", sip_utils::sip_strerror(status)); acc->messageEngine_.onMessageSent(to, id, false); } return; } else { JAMI_ERROR("Unable to add Authorization Header into msg"); acc->messageEngine_.onMessageSent(c->to, c->id, false); return; } } acc->messageEngine_.onMessageSent(c->to, c->id, event && event->body.tsx_state.tsx && (event->body.tsx_state.tsx->status_code == PJSIP_SC_OK || event->body.tsx_state.tsx->status_code == PJSIP_SC_ACCEPTED)); } std::string SIPAccount::getUserUri() const { return getFromUri(); } dhtnet::IpAddr SIPAccount::createBindingAddress() { auto family = hostIp_ ? hostIp_.getFamily() : PJ_AF_INET; const auto& conf = config(); dhtnet::IpAddr ret = conf.bindAddress.empty() ? ( conf.interface == dhtnet::ip_utils::DEFAULT_INTERFACE || conf.interface.empty() ? dhtnet::ip_utils::getAnyHostAddr(family) : dhtnet::ip_utils::getInterfaceAddr(getLocalInterface(), family)) : dhtnet::IpAddr(conf.bindAddress, family); if (ret.getPort() == 0) { ret.setPort(conf.tlsEnable ? conf.tlsListenerPort : conf.localPort); } return ret; } void SIPAccount::setActiveCodecs(const std::vector<unsigned>& list) { Account::setActiveCodecs(list); if (!hasActiveCodec(MEDIA_AUDIO)) { JAMI_WARNING("All audio codecs disabled, enabling all"); setAllCodecsActive(MEDIA_AUDIO, true); } if (!hasActiveCodec(MEDIA_VIDEO)) { JAMI_WARNING("All video codecs disabled, enabling all"); setAllCodecsActive(MEDIA_VIDEO, true); } config_->activeCodecs = getActiveCodecs(MEDIA_ALL); } } // namespace jami
68,488
C++
.cpp
1,706
30.900352
102
0.598051
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,837
sippresence.cpp
savoirfairelinux_jami-daemon/src/sip/sippresence.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sip/sippresence.h" #include "logger.h" #include "manager.h" #include "sip/sipaccount.h" #include "connectivity/sip_utils.h" #include "pres_sub_server.h" #include "pres_sub_client.h" #include "sip/sipvoiplink.h" #include "client/ring_signal.h" #include "connectivity/sip_utils.h" #include <opendht/crypto.h> #include <fmt/core.h> #include <thread> #include <sstream> #define MAX_N_SUB_SERVER 50 #define MAX_N_SUB_CLIENT 50 namespace jami { using sip_utils::CONST_PJ_STR; SIPPresence::SIPPresence(SIPAccount* acc) : publish_sess_() , status_data_() , enabled_(false) , publish_supported_(false) , subscribe_supported_(false) , status_(false) , note_(" ") , acc_(acc) , sub_server_list_() // IP2IP context , sub_client_list_() , cp_() , pool_() { /* init pool */ pj_caching_pool_init(&cp_, &pj_pool_factory_default_policy, 0); pool_ = pj_pool_create(&cp_.factory, "pres", 1000, 1000, NULL); if (!pool_) throw std::runtime_error("Unable to allocate pool for presence"); /* init default status */ updateStatus(false, " "); } SIPPresence::~SIPPresence() { /* Flush the lists */ // FIXME: Unable to destroy/unsubscribe buddies properly. // Is the transport usable when the account is being destroyed? // for (const auto & c : sub_client_list_) // delete(c); sub_client_list_.clear(); sub_server_list_.clear(); pj_pool_release(pool_); pj_caching_pool_destroy(&cp_); } SIPAccount* SIPPresence::getAccount() const { return acc_; } pjsip_pres_status* SIPPresence::getStatus() { return &status_data_; } int SIPPresence::getModId() const { return Manager::instance().sipVoIPLink().getModId(); } pj_pool_t* SIPPresence::getPool() const { return pool_; } void SIPPresence::enable(bool enabled) { enabled_ = enabled; } void SIPPresence::support(int function, bool supported) { if (function == PRESENCE_FUNCTION_PUBLISH) publish_supported_ = supported; else if (function == PRESENCE_FUNCTION_SUBSCRIBE) subscribe_supported_ = supported; } bool SIPPresence::isSupported(int function) { if (function == PRESENCE_FUNCTION_PUBLISH) return publish_supported_; else if (function == PRESENCE_FUNCTION_SUBSCRIBE) return subscribe_supported_; return false; } void SIPPresence::updateStatus(bool status, const std::string& note) { // char* pj_note = (char*) pj_pool_alloc(pool_, "50"); pjrpid_element rpid = {PJRPID_ELEMENT_TYPE_PERSON, CONST_PJ_STR("0"), PJRPID_ACTIVITY_UNKNOWN, CONST_PJ_STR(note)}; /* fill activity if user not available. */ if (note == "away") rpid.activity = PJRPID_ACTIVITY_AWAY; else if (note == "busy") rpid.activity = PJRPID_ACTIVITY_BUSY; /* else // TODO: is there any other possibilities JAMI_DBG("Presence : no activity"); */ pj_bzero(&status_data_, sizeof(status_data_)); status_data_.info_cnt = 1; status_data_.info[0].basic_open = status; // at most we will have 3 digits + NULL termination char buf[4]; pj_utoa(rand() % 1000, buf); status_data_.info[0].id = pj_strdup3(pool_, buf); pj_memcpy(&status_data_.info[0].rpid, &rpid, sizeof(pjrpid_element)); /* "contact" field is optionnal */ } void SIPPresence::sendPresence(bool status, const std::string& note) { updateStatus(status, note); // if ((not publish_supported_) or (not enabled_)) // return; if (acc_->isIP2IP()) notifyPresSubServer(); // to each subscribers else publish(this); // to the PBX server } void SIPPresence::reportPresSubClientNotification(std::string_view uri, pjsip_pres_status* status) { /* Update our info. See pjsua_buddy_get_info() for additionnal ideas*/ const std::string& acc_ID = acc_->getAccountID(); const std::string note(status->info[0].rpid.note.ptr, status->info[0].rpid.note.slen); JAMI_DBG(" Received status of PresSubClient %.*s(acc:%s): status=%s note=%s", (int)uri.size(), uri.data(), acc_ID.c_str(), status->info[0].basic_open ? "open" : "closed", note.c_str()); if (uri == acc_->getFromUri()) { // save the status of our own account status_ = status->info[0].basic_open; note_ = note; } // report status to client signal emitSignal<libjami::PresenceSignal::NewBuddyNotification>(acc_ID, std::string(uri), status->info[0].basic_open, note); } void SIPPresence::subscribeClient(const std::string& uri, bool flag) { /* if an account has a server that doesn't support SUBSCRIBE, it's still possible * to subscribe to someone on another server */ /* std::string account_host = std::string(pj_gethostname()->ptr, pj_gethostname()->slen); std::string sub_host = sip_utils::getHostFromUri(uri); if (((not subscribe_supported_) && (account_host == sub_host)) or (not enabled_)) return; */ /* Check if the buddy was already subscribed */ for (const auto& c : sub_client_list_) { if (c->getURI() == uri) { // JAMI_DBG("-PresSubClient:%s exists in the list. Replace it.", uri.c_str()); if (flag) c->subscribe(); else c->unsubscribe(); return; } } if (sub_client_list_.size() >= MAX_N_SUB_CLIENT) { JAMI_WARN("Unable to add PresSubClient, max number reached."); return; } if (flag) { PresSubClient* c = new PresSubClient(uri, this); if (!(c->subscribe())) { JAMI_WARN("Failed send subscribe."); delete c; } // the buddy has to be accepted before being added in the list } } void SIPPresence::addPresSubClient(PresSubClient* c) { if (sub_client_list_.size() < MAX_N_SUB_CLIENT) { sub_client_list_.push_back(c); JAMI_DBG("New Presence_subscription_client added (list[%zu]).", sub_client_list_.size()); } else { JAMI_WARN("Max Presence_subscription_client is reach."); // let the client alive //delete c; } } void SIPPresence::removePresSubClient(PresSubClient* c) { JAMI_DBG("Remove Presence_subscription_client from the buddy list."); sub_client_list_.remove(c); } void SIPPresence::approvePresSubServer(const std::string& uri, bool flag) { for (const auto& s : sub_server_list_) { if (s->matches((char*) uri.c_str())) { s->approve(flag); // return; // 'return' would prevent multiple-time subscribers from spam } } } void SIPPresence::addPresSubServer(PresSubServer* s) { if (sub_server_list_.size() < MAX_N_SUB_SERVER) { sub_server_list_.push_back(s); } else { JAMI_WARN("Max Presence_subscription_server is reach."); // let de server alive // delete s; } } void SIPPresence::removePresSubServer(PresSubServer* s) { sub_server_list_.remove(s); JAMI_DBG("Presence_subscription_server removed"); } void SIPPresence::notifyPresSubServer() { JAMI_DBG("Iterating through IP2IP Presence_subscription_server:"); for (const auto& s : sub_server_list_) s->notify(); } void SIPPresence::lock() { mutex_.lock(); } bool SIPPresence::tryLock() { return mutex_.try_lock(); } void SIPPresence::unlock() { mutex_.unlock(); } void SIPPresence::fillDoc(pjsip_tx_data* tdata, const pres_msg_data* msg_data) { if (tdata->msg->type == PJSIP_REQUEST_MSG) { constexpr pj_str_t STR_USER_AGENT = CONST_PJ_STR("User-Agent"); std::string useragent(acc_->getUserAgentName()); pj_str_t pJuseragent = pj_str((char*) useragent.c_str()); pjsip_hdr* h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool, &STR_USER_AGENT, &pJuseragent); pjsip_msg_add_hdr(tdata->msg, h); } if (msg_data == NULL) return; const pjsip_hdr* hdr; hdr = msg_data->hdr_list.next; while (hdr && hdr != &msg_data->hdr_list) { pjsip_hdr* new_hdr; new_hdr = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, hdr); JAMI_DBG("adding header %p", new_hdr->name.ptr); pjsip_msg_add_hdr(tdata->msg, new_hdr); hdr = hdr->next; } if (msg_data->content_type.slen && msg_data->msg_body.slen) { pjsip_msg_body* body; constexpr pj_str_t type = CONST_PJ_STR("application"); constexpr pj_str_t subtype = CONST_PJ_STR("pidf+xml"); body = pjsip_msg_body_create(tdata->pool, &type, &subtype, &msg_data->msg_body); tdata->msg->body = body; } } static const pjsip_publishc_opt my_publish_opt = {true}; // this is queue_request /* * Client presence publication callback. */ void SIPPresence::publish_cb(struct pjsip_publishc_cbparam* param) { SIPPresence* pres = (SIPPresence*) param->token; if (param->code / 100 != 2 || param->status != PJ_SUCCESS) { pjsip_publishc_destroy(param->pubc); pres->publish_sess_ = NULL; std::string error = fmt::format("{} / {}", param->code, sip_utils::as_view(param->reason)); if (param->status != PJ_SUCCESS) { char errmsg[PJ_ERR_MSG_SIZE]; pj_strerror(param->status, errmsg, sizeof(errmsg)); JAMI_ERR("Client (PUBLISH) failed, status=%d, msg=%s", param->status, errmsg); emitSignal<libjami::PresenceSignal::ServerError>(pres->getAccount()->getAccountID(), error, errmsg); } else if (param->code == 412) { /* 412 (Conditional Request Failed) * The PUBLISH refresh has failed, retry with new one. */ JAMI_WARN("Publish retry."); publish(pres); } else if ((param->code == PJSIP_SC_BAD_EVENT) || (param->code == PJSIP_SC_NOT_IMPLEMENTED)) { // 489 or 501 JAMI_WARN("Client (PUBLISH) failed (%s)", error.c_str()); emitSignal<libjami::PresenceSignal::ServerError>(pres->getAccount()->getAccountID(), error, "Publish not supported."); pres->getAccount()->supportPresence(PRESENCE_FUNCTION_PUBLISH, false); } } else { if (param->expiration < 1) { /* Could happen if server "forgot" to include Expires header * in the response. We will not renew, so destroy the pubc. */ pjsip_publishc_destroy(param->pubc); pres->publish_sess_ = NULL; } pres->getAccount()->supportPresence(PRESENCE_FUNCTION_PUBLISH, true); } } /* * Send PUBLISH request. */ pj_status_t SIPPresence::send_publish(SIPPresence* pres) { pjsip_tx_data* tdata; pj_status_t status; JAMI_DBG("Send PUBLISH (%s).", pres->getAccount()->getAccountID().c_str()); SIPAccount* acc = pres->getAccount(); std::string contactWithAngles = acc->getFromUri(); contactWithAngles.erase(contactWithAngles.find('>')); int semicolon = contactWithAngles.find_first_of(':'); std::string contactWithoutAngles = contactWithAngles.substr(semicolon + 1); // pj_str_t contact = pj_str(strdup(contactWithoutAngles.c_str())); // pj_memcpy(&status_data.info[0].contact, &contt, sizeof(pj_str_t));; /* Create PUBLISH request */ char* bpos; pj_str_t entity; status = pjsip_publishc_publish(pres->publish_sess_, PJ_TRUE, &tdata); pj_str_t from = pj_strdup3(pres->pool_, acc->getFromUri().c_str()); if (status != PJ_SUCCESS) { JAMI_ERR("Error creating PUBLISH request %d", status); goto on_error; } if ((bpos = pj_strchr(&from, '<')) != NULL) { char* epos = pj_strchr(&from, '>'); if (epos - bpos < 2) { JAMI_ERR("Unexpected invalid URI"); status = PJSIP_EINVALIDURI; goto on_error; } entity.ptr = bpos + 1; entity.slen = epos - bpos - 1; } else { entity = from; } /* Create and add PIDF message body */ status = pjsip_pres_create_pidf(tdata->pool, pres->getStatus(), &entity, &tdata->msg->body); pres_msg_data msg_data; if (status != PJ_SUCCESS) { JAMI_ERR("Error creating PIDF for PUBLISH request"); pjsip_tx_data_dec_ref(tdata); goto on_error; } pj_bzero(&msg_data, sizeof(msg_data)); pj_list_init(&msg_data.hdr_list); pjsip_media_type_init(&msg_data.multipart_ctype, NULL, NULL); pj_list_init(&msg_data.multipart_parts); pres->fillDoc(tdata, &msg_data); /* Send the PUBLISH request */ status = pjsip_publishc_send(pres->publish_sess_, tdata); if (status == PJ_EPENDING) { JAMI_WARN("Previous request is in progress, "); } else if (status != PJ_SUCCESS) { JAMI_ERR("Error sending PUBLISH request"); goto on_error; } return PJ_SUCCESS; on_error: if (pres->publish_sess_) { pjsip_publishc_destroy(pres->publish_sess_); pres->publish_sess_ = NULL; } return status; } /* Create client publish session */ pj_status_t SIPPresence::publish(SIPPresence* pres) { pj_status_t status; constexpr pj_str_t STR_PRESENCE = CONST_PJ_STR("presence"); SIPAccount* acc = pres->getAccount(); pjsip_endpoint* endpt = Manager::instance().sipVoIPLink().getEndpoint(); /* Create and init client publication session */ /* Create client publication */ status = pjsip_publishc_create(endpt, &my_publish_opt, pres, &publish_cb, &pres->publish_sess_); if (status != PJ_SUCCESS) { pres->publish_sess_ = NULL; JAMI_ERR("Failed to create a publish session."); return status; } /* Initialize client publication */ pj_str_t from = pj_strdup3(pres->pool_, acc->getFromUri().c_str()); status = pjsip_publishc_init(pres->publish_sess_, &STR_PRESENCE, &from, &from, &from, 0xFFFF); if (status != PJ_SUCCESS) { JAMI_ERR("Failed to init a publish session"); pres->publish_sess_ = NULL; return status; } /* Add credential for authentication */ if (acc->hasCredentials() and pjsip_publishc_set_credentials(pres->publish_sess_, acc->getCredentialCount(), acc->getCredInfo()) != PJ_SUCCESS) { JAMI_ERR("Unable to initialize credentials for invite session authentication"); return status; } /* Set route-set */ // FIXME: is this really necessary? pjsip_regc* regc = acc->getRegistrationInfo(); if (regc and acc->hasServiceRoute()) pjsip_regc_set_route_set(regc, sip_utils::createRouteSet(acc->getServiceRoute(), pres->getPool())); /* Send initial PUBLISH request */ status = send_publish(pres); if (status != PJ_SUCCESS) return status; return PJ_SUCCESS; } } // namespace jami
16,232
C++
.cpp
458
28.519651
101
0.610838
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,838
sipaccountbase.cpp
savoirfairelinux_jami-daemon/src/sip/sipaccountbase.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sip/sipaccountbase.h" #include "sip/sipvoiplink.h" #ifdef ENABLE_VIDEO #include "libav_utils.h" #endif #include "account_schema.h" #include "manager.h" #include "config/yamlparser.h" #include "client/ring_signal.h" #include "jami/account_const.h" #include "string_utils.h" #include "fileutils.h" #include "connectivity/sip_utils.h" #include "connectivity/utf8_utils.h" #include "uri.h" #ifdef ENABLE_PLUGIN #include "plugin/jamipluginmanager.h" #include "plugin/streamdata.h" #endif #include <dhtnet/ice_transport.h> #include <dhtnet/ice_transport_factory.h> #include <fmt/core.h> #include <json/json.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <yaml-cpp/yaml.h> #pragma GCC diagnostic pop #include <type_traits> #include <regex> #include <ctime> using namespace std::literals; namespace jami { SIPAccountBase::SIPAccountBase(const std::string& accountID) : Account(accountID) , messageEngine_(*this, (fileutils::get_cache_dir() / getAccountID() / "messages").string()) , link_(Manager::instance().sipVoIPLink()) {} SIPAccountBase::~SIPAccountBase() noexcept {} bool SIPAccountBase::CreateClientDialogAndInvite(const pj_str_t* from, const pj_str_t* contact, const pj_str_t* to, const pj_str_t* target, const pjmedia_sdp_session* local_sdp, pjsip_dialog** dlg, pjsip_inv_session** inv) { JAMI_DBG("Creating SIP dialog: \n" "From: %s\n" "Contact: %s\n" "To: %s\n", from->ptr, contact->ptr, to->ptr); if (target) { JAMI_DBG("Target: %s", target->ptr); } else { JAMI_DBG("No target provided, using 'to' as target"); } auto status = pjsip_dlg_create_uac(pjsip_ua_instance(), from, contact, to, target, dlg); if (status != PJ_SUCCESS) { JAMI_ERR("Unable to create SIP dialogs for user agent client when calling %s %d", to->ptr, status); return false; } auto dialog = *dlg; { // lock dialog until invite session creation; this one will own the dialog after sip_utils::PJDialogLock dlg_lock {dialog}; // Append "Subject: Phone Call" header constexpr auto subj_hdr_name = sip_utils::CONST_PJ_STR("Subject"); auto subj_hdr = reinterpret_cast<pjsip_hdr*>( pjsip_parse_hdr(dialog->pool, &subj_hdr_name, const_cast<char*>("Phone call"), 10, nullptr)); pj_list_push_back(&dialog->inv_hdr, subj_hdr); if (pjsip_inv_create_uac(dialog, local_sdp, 0, inv) != PJ_SUCCESS) { JAMI_ERR("Unable to create invite session for user agent client"); return false; } } return true; } void SIPAccountBase::flush() { // Class base method Account::flush(); dhtnet::fileutils::remove(fileutils::get_cache_dir() / getAccountID() / "messages"); } void SIPAccountBase::loadConfig() { Account::loadConfig(); const auto& conf = config(); dhtnet::IpAddr publishedIp {conf.publishedIp}; if (not conf.publishedSameasLocal and publishedIp) setPublishedAddress(publishedIp); dhtnet::TurnTransportParams turnParams; turnParams.domain = conf.turnServer; turnParams.username = conf.turnServerUserName; turnParams.password = conf.turnServerPwd; turnParams.realm = conf.turnServerRealm; if (!turnCache_) { auto cachePath = fileutils::get_cache_dir() / getAccountID(); turnCache_ = std::make_shared<dhtnet::TurnCache>(getAccountID(), cachePath.string(), Manager::instance().ioContext(), Logger::dhtLogger(), turnParams, conf.turnEnabled); } turnCache_->reconfigure(turnParams, conf.turnEnabled); } std::map<std::string, std::string> SIPAccountBase::getVolatileAccountDetails() const { auto a = Account::getVolatileAccountDetails(); // replace value from Account for IP2IP if (isIP2IP()) a[Conf::CONFIG_ACCOUNT_REGISTRATION_STATUS] = "READY"; a.emplace(Conf::CONFIG_TRANSPORT_STATE_CODE, std::to_string(transportStatus_)); a.emplace(Conf::CONFIG_TRANSPORT_STATE_DESC, transportError_); return a; } void SIPAccountBase::setRegistrationState(RegistrationState state, int details_code, const std::string& details_str) { if (state == RegistrationState::REGISTERED && registrationState_ != RegistrationState::REGISTERED) messageEngine_.load(); else if (state != RegistrationState::REGISTERED && registrationState_ == RegistrationState::REGISTERED) messageEngine_.save(); Account::setRegistrationState(state, details_code, details_str); } auto SIPAccountBase::getPortsReservation() noexcept -> decltype(getPortsReservation()) { // Note: static arrays are zero-initialized static std::remove_reference<decltype(getPortsReservation())>::type portsInUse; return portsInUse; } uint16_t SIPAccountBase::getRandomEvenPort(const std::pair<uint16_t, uint16_t>& range) const { std::uniform_int_distribution<uint16_t> dist(range.first / 2, range.second / 2); uint16_t result; do { result = 2 * dist(rand); } while (getPortsReservation()[result / 2]); return result; } uint16_t SIPAccountBase::acquireRandomEvenPort(const std::pair<uint16_t, uint16_t>& range) const { std::uniform_int_distribution<uint16_t> dist(range.first / 2, range.second / 2); uint16_t result; do { result = 2 * dist(rand); } while (getPortsReservation()[result / 2]); getPortsReservation()[result / 2] = true; return result; } uint16_t SIPAccountBase::acquirePort(uint16_t port) { getPortsReservation()[port / 2] = true; return port; } void SIPAccountBase::releasePort(uint16_t port) noexcept { getPortsReservation()[port / 2] = false; } uint16_t SIPAccountBase::generateAudioPort() const { return acquireRandomEvenPort(config().audioPortRange); } #ifdef ENABLE_VIDEO uint16_t SIPAccountBase::generateVideoPort() const { return acquireRandomEvenPort(config().videoPortRange); } #endif dhtnet::IceTransportOptions SIPAccountBase::getIceOptions() const noexcept { dhtnet::IceTransportOptions opts; opts.upnpEnable = getUPnPActive(); opts.upnpContext = upnpCtrl_ ? upnpCtrl_->upnpContext() : nullptr; opts.factory = Manager::instance().getIceTransportFactory(); if (config().turnEnabled && turnCache_) { auto turnAddr = turnCache_->getResolvedTurn(); if (turnAddr != std::nullopt) { opts.turnServers.emplace_back(dhtnet::TurnServerInfo() .setUri(turnAddr->toString(true)) .setUsername(config().turnServerUserName) .setPassword(config().turnServerPwd) .setRealm(config().turnServerRealm)); } // NOTE: first test with ipv6 turn was not concluant and resulted in multiple // co issues. So this needs some debug. for now just disable // if (cacheTurnV6_ && *cacheTurnV6_) { // opts.turnServers.emplace_back(TurnServerInfo() // .setUri(cacheTurnV6_->toString(true)) // .setUsername(turnServerUserName_) // .setPassword(turnServerPwd_) // .setRealm(turnServerRealm_)); //} } return opts; } void SIPAccountBase::onTextMessage(const std::string& id, const std::string& from, const std::string& /* deviceId */, const std::map<std::string, std::string>& payloads) { JAMI_DBG("Text message received from %s, %zu part(s)", from.c_str(), payloads.size()); for (const auto& m : payloads) { if (!utf8_validate(m.first)) return; if (!utf8_validate(m.second)) { JAMI_WARN("Dropping invalid message with MIME type %s", m.first.c_str()); return; } if (handleMessage(from, m)) return; } #ifdef ENABLE_PLUGIN auto& pluginChatManager = Manager::instance().getJamiPluginManager().getChatServicesManager(); if (pluginChatManager.hasHandlers()) { pluginChatManager.publishMessage( std::make_shared<JamiMessage>(accountID_, from, true, payloads, false)); } #endif emitSignal<libjami::ConfigurationSignal::IncomingAccountMessage>(accountID_, from, id, payloads); libjami::Message message; message.from = from; message.payloads = payloads; message.received = std::time(nullptr); std::lock_guard lck(mutexLastMessages_); lastMessages_.emplace_back(std::move(message)); while (lastMessages_.size() > MAX_WAITING_MESSAGES_SIZE) { lastMessages_.pop_front(); } } dhtnet::IpAddr SIPAccountBase::getPublishedIpAddress(uint16_t family) const { if (family == AF_INET) return publishedIp_[0]; if (family == AF_INET6) return publishedIp_[1]; assert(family == AF_UNSPEC); // If family is not set, prefere IPv4 if available. It's more // likely to succeed behind NAT. if (publishedIp_[0]) return publishedIp_[0]; if (publishedIp_[1]) return publishedIp_[1]; return {}; } void SIPAccountBase::setPublishedAddress(const dhtnet::IpAddr& ip_addr) { if (ip_addr.getFamily() == AF_INET) { publishedIp_[0] = ip_addr; } else { publishedIp_[1] = ip_addr; } } std::vector<libjami::Message> SIPAccountBase::getLastMessages(const uint64_t& base_timestamp) { std::lock_guard lck(mutexLastMessages_); auto it = lastMessages_.begin(); size_t num = lastMessages_.size(); while (it != lastMessages_.end() and it->received <= base_timestamp) { num--; ++it; } if (num == 0) return {}; return {it, lastMessages_.end()}; } std::vector<MediaAttribute> SIPAccountBase::createDefaultMediaList(bool addVideo, bool onHold) { std::vector<MediaAttribute> mediaList; bool secure = isSrtpEnabled(); // Add audio and DTMF events mediaList.emplace_back(MediaAttribute(MediaType::MEDIA_AUDIO, false, secure, true, "", sip_utils::DEFAULT_AUDIO_STREAMID, onHold)); #ifdef ENABLE_VIDEO // Add video if allowed. if (isVideoEnabled() and addVideo) { mediaList.emplace_back(MediaAttribute(MediaType::MEDIA_VIDEO, false, secure, true, "", sip_utils::DEFAULT_VIDEO_STREAMID, onHold)); } #endif return mediaList; } } // namespace jami
12,616
C++
.cpp
338
28.505917
101
0.599575
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,839
sipvoiplink.cpp
savoirfairelinux_jami-daemon/src/sip/sipvoiplink.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sip/sipvoiplink.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sdp.h" #include "sip/sipcall.h" #include "sip/sipaccount.h" #include "jamidht/jamiaccount.h" #include "manager.h" #include "im/instant_messaging.h" #include "system_codec_container.h" #include "audio/audio_rtp_session.h" #ifdef ENABLE_VIDEO #include "video/video_rtp_session.h" #include "client/videomanager.h" #endif #include "pres_sub_server.h" #include "connectivity/sip_utils.h" #include "string_utils.h" #include "logger.h" #include <dhtnet/ip_utils.h> #include <opendht/thread_pool.h> #include <pjsip/sip_endpoint.h> #include <pjsip/sip_uri.h> #include <pjsip-simple/presence.h> #include <pjsip-simple/publish.h> // Only PJSIP 2.10 is supported. #if PJ_VERSION_NUM < (2 << 24 | 10 << 16) #error "Unsupported PJSIP version (requires version 2.10+)" #endif #include <istream> #include <algorithm> #include <regex> namespace jami { using sip_utils::CONST_PJ_STR; /**************** EXTERN VARIABLES AND FUNCTIONS (callbacks) **************************/ static pjsip_endpoint* endpt_; static pjsip_module mod_ua_; static void invite_session_state_changed_cb(pjsip_inv_session* inv, pjsip_event* e); static void outgoing_request_forked_cb(pjsip_inv_session* inv, pjsip_event* e); static void transaction_state_changed_cb(pjsip_inv_session* inv, pjsip_transaction* tsx, pjsip_event* e); // Called when an SDP offer is found in answer. This will occur // when we send an empty invite (no SDP). In this case, we should // expect an offer in a the 200 OK message static void on_rx_offer2(pjsip_inv_session* inv, struct pjsip_inv_on_rx_offer_cb_param* param); // Called when a re-invite is received static pj_status_t reinvite_received_cb(pjsip_inv_session* inv, const pjmedia_sdp_session* offer, pjsip_rx_data* rdata); // Called to request an SDP offer if the peer sent an invite or // a re-invite with no SDP. In this, we must provide an offer in // the answer (200 OK) if we accept the call static void sdp_create_offer_cb(pjsip_inv_session* inv, pjmedia_sdp_session** p_offer); // Called to report media (SDP) negotiation result static void sdp_media_update_cb(pjsip_inv_session* inv, pj_status_t status); static std::shared_ptr<SIPCall> getCallFromInvite(pjsip_inv_session* inv); #ifdef DEBUG_SIP_REQUEST_MSG static void processInviteResponseHelper(pjsip_inv_session* inv, pjsip_event* e); #endif static pj_bool_t handleIncomingOptions(pjsip_rx_data* rdata) { pjsip_tx_data* tdata; auto dlg = pjsip_rdata_get_dlg(rdata); if (dlg) { JAMI_INFO("Processing in-dialog option request"); if (pjsip_dlg_create_response(dlg, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS) { JAMI_ERR("Failed to create in-dialog response for option request"); return PJ_FALSE; } } else { JAMI_INFO("Processing out-of-dialog option request"); if (pjsip_endpt_create_response(endpt_, rdata, PJSIP_SC_OK, NULL, &tdata) != PJ_SUCCESS) { JAMI_ERR("Failed to create out-of-dialog response for option request"); return PJ_FALSE; } } #define ADD_HDR(hdr) \ do { \ const pjsip_hdr* cap_hdr = hdr; \ if (cap_hdr) \ pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, cap_hdr)); \ } while (0) #define ADD_CAP(cap) ADD_HDR(pjsip_endpt_get_capability(endpt_, cap, NULL)); ADD_CAP(PJSIP_H_ALLOW); ADD_CAP(PJSIP_H_ACCEPT); ADD_CAP(PJSIP_H_SUPPORTED); ADD_HDR(pjsip_evsub_get_allow_events_hdr(NULL)); if (dlg) { if (pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata) != PJ_SUCCESS) { JAMI_ERR("Failed to send in-dialog response for option request"); return PJ_FALSE; } JAMI_INFO("Sent in-dialog response for option request"); return PJ_TRUE; } pjsip_response_addr res_addr; pjsip_get_response_addr(tdata->pool, rdata, &res_addr); if (pjsip_endpt_send_response(endpt_, &res_addr, tdata, NULL, NULL) != PJ_SUCCESS) { pjsip_tx_data_dec_ref(tdata); JAMI_ERR("Failed to send out-of-dialog response for option request"); return PJ_FALSE; } JAMI_INFO("Sent out-of-dialog response for option request"); return PJ_TRUE; } // return PJ_FALSE so that eventually other modules will handle these requests // TODO: move Voicemail to separate module static pj_bool_t transaction_response_cb(pjsip_rx_data* rdata) { pjsip_dialog* dlg = pjsip_rdata_get_dlg(rdata); if (!dlg) return PJ_FALSE; pjsip_transaction* tsx = pjsip_rdata_get_tsx(rdata); if (!tsx or tsx->method.id != PJSIP_INVITE_METHOD) return PJ_FALSE; if (tsx->status_code / 100 == 2) { /** * Send an ACK message inside a transaction. PJSIP send automatically, non-2xx ACK response. * ACK for a 2xx response must be send using this method. */ pjsip_tx_data* tdata; if (rdata->msg_info.cseq) { pjsip_dlg_create_request(dlg, &pjsip_ack_method, rdata->msg_info.cseq->cseq, &tdata); pjsip_dlg_send_request(dlg, tdata, -1, NULL); } } return PJ_FALSE; } static pj_status_t try_respond_stateless(pjsip_endpoint* endpt, pjsip_rx_data* rdata, int st_code, const pj_str_t* st_text, const pjsip_hdr* hdr_list, const pjsip_msg_body* body) { /* Check that no UAS transaction has been created for this request. * If UAS transaction has been created for this request, application * MUST send the response statefully using that transaction. */ if (!pjsip_rdata_get_tsx(rdata)) return pjsip_endpt_respond_stateless(endpt, rdata, st_code, st_text, hdr_list, body); else JAMI_ERR("Transaction has been created for this request, send response " "statefully instead"); return !PJ_SUCCESS; } template<typename T> bool is_uninitialized(std::weak_ptr<T> const& weak) { using wt = std::weak_ptr<T>; return !weak.owner_before(wt {}) && !wt {}.owner_before(weak); } static pj_bool_t transaction_request_cb(pjsip_rx_data* rdata) { if (!rdata or !rdata->msg_info.msg) { JAMI_ERR("rx_data is NULL"); return PJ_FALSE; } pjsip_method* method = &rdata->msg_info.msg->line.req.method; if (!method) { JAMI_ERR("method is NULL"); return PJ_FALSE; } if (method->id == PJSIP_ACK_METHOD && pjsip_rdata_get_dlg(rdata)) return PJ_FALSE; if (!rdata->msg_info.to or !rdata->msg_info.from or !rdata->msg_info.via) { JAMI_ERR("Missing From, To or Via fields"); return PJ_FALSE; } const auto sip_to_uri = reinterpret_cast<pjsip_sip_uri*>( pjsip_uri_get_uri(rdata->msg_info.to->uri)); const auto sip_from_uri = reinterpret_cast<pjsip_sip_uri*>( pjsip_uri_get_uri(rdata->msg_info.from->uri)); const pjsip_host_port& sip_via = rdata->msg_info.via->sent_by; if (!sip_to_uri or !sip_from_uri or !sip_via.host.ptr) { JAMI_ERR("NULL uri"); return PJ_FALSE; } std::string_view toUsername(sip_to_uri->user.ptr, sip_to_uri->user.slen); std::string_view toHost(sip_to_uri->host.ptr, sip_to_uri->host.slen); std::string_view viaHostname(sip_via.host.ptr, sip_via.host.slen); const std::string_view remote_user(sip_from_uri->user.ptr, sip_from_uri->user.slen); const std::string_view remote_hostname(sip_from_uri->host.ptr, sip_from_uri->host.slen); std::string peerNumber; if (not remote_user.empty() and not remote_hostname.empty()) peerNumber = remote_user + "@" + remote_hostname; else { char tmp[PJSIP_MAX_URL_SIZE]; size_t length = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, sip_from_uri, tmp, PJSIP_MAX_URL_SIZE); peerNumber = sip_utils::stripSipUriPrefix(std::string_view(tmp, length)); } auto transport = Manager::instance().sipVoIPLink().sipTransportBroker->addTransport( rdata->tp_info.transport); std::shared_ptr<SIPAccountBase> account; // If transport account is default-constructed, guessing account is allowed const auto& waccount = transport ? transport->getAccount() : std::weak_ptr<SIPAccountBase> {}; if (is_uninitialized(waccount)) { account = Manager::instance().sipVoIPLink().guessAccount(toUsername, viaHostname, remote_hostname); if (not account) return PJ_FALSE; if (not transport and account->getAccountType() == SIPAccount::ACCOUNT_TYPE) { if (not(transport = std::static_pointer_cast<SIPAccount>(account)->getTransport())) { JAMI_ERR("No suitable transport to answer this call."); return PJ_FALSE; } JAMI_WARN("Using transport from account."); } } else if (!(account = waccount.lock())) { JAMI_ERR("Dropping SIP request: account is expired."); return PJ_FALSE; } pjsip_msg_body* body = rdata->msg_info.msg->body; if (method->id == PJSIP_OTHER_METHOD) { std::string_view request = sip_utils::as_view(method->name); if (request.find(sip_utils::SIP_METHODS::NOTIFY) != std::string_view::npos) { if (body and body->data) { std::string_view body_view(static_cast<char*>(body->data), body->len); auto pos = body_view.find("Voice-Message: "); if (pos != std::string_view::npos) { int newCount {0}; int oldCount {0}; int urgentCount {0}; std::string sp(body_view.substr(pos)); int ret = sscanf(sp.c_str(), "Voice-Message: %d/%d (%d/", &newCount, &oldCount, &urgentCount); // According to rfc3842 // urgent messages are optional if (ret >= 2) emitSignal<libjami::CallSignal::VoiceMailNotify>(account->getAccountID(), newCount, oldCount, urgentCount); } } } else if (request.find(sip_utils::SIP_METHODS::MESSAGE) != std::string_view::npos) { // Reply 200 immediately (RFC 3428, ch. 7) try_respond_stateless(endpt_, rdata, PJSIP_SC_OK, nullptr, nullptr, nullptr); // Process message content in case of multi-part body auto payloads = im::parseSipMessage(rdata->msg_info.msg); if (payloads.size() > 0) { constexpr pj_str_t STR_MESSAGE_ID = jami::sip_utils::CONST_PJ_STR("Message-ID"); auto* msgId = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_MESSAGE_ID, nullptr); std::string id = {}; if (!msgId) { // Supports imdn message format https://tools.ietf.org/html/rfc5438#section-7.1.1.3 constexpr pj_str_t STR_IMDN_MESSAGE_ID = jami::sip_utils::CONST_PJ_STR( "imdn.Message-ID"); msgId = (pjsip_generic_string_hdr*) pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_IMDN_MESSAGE_ID, nullptr); } if (msgId) id = std::string(msgId->hvalue.ptr, msgId->hvalue.slen); if (not id.empty()) { try { // Mark message as treated auto intid = from_hex_string(id); auto acc = std::dynamic_pointer_cast<JamiAccount>(account); if (acc and acc->isMessageTreated(intid)) return PJ_FALSE; } catch (...) { } } account->onTextMessage(id, peerNumber, std::string(transport->deviceId()), payloads); } return PJ_FALSE; } try_respond_stateless(endpt_, rdata, PJSIP_SC_OK, NULL, NULL, NULL); return PJ_FALSE; } else if (method->id == PJSIP_OPTIONS_METHOD) { return handleIncomingOptions(rdata); } else if (method->id != PJSIP_INVITE_METHOD && method->id != PJSIP_ACK_METHOD) { try_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); return PJ_FALSE; } if (method->id == PJSIP_INVITE_METHOD) { // Log headers of received INVITE JAMI_INFO("Received a SIP INVITE request"); sip_utils::logMessageHeaders(&rdata->msg_info.msg->hdr); } pjmedia_sdp_session* r_sdp {nullptr}; if (body) { if (pjmedia_sdp_parse(rdata->tp_info.pool, (char*) body->data, body->len, &r_sdp) != PJ_SUCCESS) { JAMI_WARN("Failed to parse the SDP in offer"); r_sdp = nullptr; } } if (not account->hasActiveCodec(MEDIA_AUDIO)) { try_respond_stateless(endpt_, rdata, PJSIP_SC_NOT_ACCEPTABLE_HERE, NULL, NULL, NULL); return PJ_FALSE; } // Verify that we can handle the request unsigned options = 0; if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, endpt_, NULL) != PJ_SUCCESS) { JAMI_ERR("Unable to verify INVITE request in secure dialog."); try_respond_stateless(endpt_, rdata, PJSIP_SC_METHOD_NOT_ALLOWED, NULL, NULL, NULL); return PJ_FALSE; } // Build the initial media using the remote offer. auto localMediaList = Sdp::getMediaAttributeListFromSdp(r_sdp); // To enable video, it must be enabled in the remote and locally (i.e. in the account) for (auto& media : localMediaList) { if (media.type_ == MediaType::MEDIA_VIDEO) { media.enabled_ &= account->isVideoEnabled(); } } auto call = account->newIncomingCall(std::string(remote_user), MediaAttribute::mediaAttributesToMediaMaps(localMediaList), transport); if (!call) { return PJ_FALSE; } call->setPeerUaVersion(sip_utils::getPeerUserAgent(rdata)); // The username can be used to join specific calls in conversations call->toUsername(std::string(toUsername)); // FIXME : for now, use the same address family as the SIP transport auto family = pjsip_transport_type_get_af( pjsip_transport_get_type_from_flag(transport->get()->flag)); dhtnet::IpAddr addrSdp; if (account->getUPnPActive()) { /* use UPnP addr, or published addr if its set */ addrSdp = account->getPublishedSameasLocal() ? account->getUPnPIpAddress() : account->getPublishedIpAddress(); } else { addrSdp = account->isStunEnabled() or (not account->getPublishedSameasLocal()) ? account->getPublishedIpAddress() : dhtnet::ip_utils::getInterfaceAddr(account->getLocalInterface(), family); } /* fallback on local address */ if (not addrSdp) addrSdp = dhtnet::ip_utils::getInterfaceAddr(account->getLocalInterface(), family); // Try to obtain display name from From: header first, fallback on Contact: auto peerDisplayName = sip_utils::parseDisplayName(rdata->msg_info.from); if (peerDisplayName.empty()) { if (auto hdr = static_cast<const pjsip_contact_hdr*>( pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, nullptr))) { peerDisplayName = sip_utils::parseDisplayName(hdr); } } call->setPeerNumber(peerNumber); call->setPeerUri(account->getToUri(peerNumber)); call->setPeerDisplayName(peerDisplayName); call->setState(Call::ConnectionState::PROGRESSING); call->getSDP().setPublishedIP(addrSdp); call->setPeerAllowMethods(sip_utils::getPeerAllowMethods(rdata)); // Set the temporary media list. Might change when we receive // the accept from the client. if (r_sdp != nullptr) { call->getSDP().setReceivedOffer(r_sdp); } pjsip_dialog* dialog = nullptr; if (pjsip_dlg_create_uas_and_inc_lock(pjsip_ua_instance(), rdata, nullptr, &dialog) != PJ_SUCCESS) { JAMI_ERR("Unable to create uas"); call.reset(); try_respond_stateless(endpt_, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, nullptr, nullptr, nullptr); return PJ_FALSE; } pjsip_tpselector tp_sel = SIPVoIPLink::getTransportSelector(transport->get()); if (!dialog or pjsip_dlg_set_transport(dialog, &tp_sel) != PJ_SUCCESS) { JAMI_ERR("Unable to set transport for dialog"); if (dialog) pjsip_dlg_dec_lock(dialog); return PJ_FALSE; } pjsip_inv_session* inv = nullptr; // Create UAS for the invite. // The SDP is not set here, it will be done when the call is // accepted and the media attributes of the answer are known. pjsip_inv_create_uas(dialog, rdata, NULL, PJSIP_INV_SUPPORT_ICE, &inv); if (!inv) { JAMI_ERR("Call invite is not initialized"); pjsip_dlg_dec_lock(dialog); return PJ_FALSE; } // dialog is now owned by invite pjsip_dlg_dec_lock(dialog); inv->mod_data[mod_ua_.id] = call.get(); call->setInviteSession(inv); // Check whether Replaces header is present in the request and process accordingly. pjsip_dialog* replaced_dlg; pjsip_tx_data* response; if (pjsip_replaces_verify_request(rdata, &replaced_dlg, PJ_FALSE, &response) != PJ_SUCCESS) { JAMI_ERR("Something wrong with Replaces request."); call.reset(); // Something wrong with the Replaces header. if (response) { pjsip_response_addr res_addr; pjsip_get_response_addr(response->pool, rdata, &res_addr); pjsip_endpt_send_response(endpt_, &res_addr, response, NULL, NULL); } else { try_respond_stateless(endpt_, rdata, PJSIP_SC_INTERNAL_SERVER_ERROR, NULL, NULL, NULL); } return PJ_FALSE; } // Check if call has been transferred pjsip_tx_data* tdata = nullptr; if (pjsip_inv_initial_answer(call->inviteSession_.get(), rdata, PJSIP_SC_TRYING, NULL, NULL, &tdata) != PJ_SUCCESS) { JAMI_ERR("Unable to create answer TRYING"); return PJ_FALSE; } // Add user-agent header sip_utils::addUserAgentHeader(account->getUserAgentName(), tdata); if (pjsip_inv_send_msg(call->inviteSession_.get(), tdata) != PJ_SUCCESS) { JAMI_ERR("Unable to send msg TRYING"); return PJ_FALSE; } call->setState(Call::ConnectionState::TRYING); if (pjsip_inv_answer(call->inviteSession_.get(), PJSIP_SC_RINGING, NULL, NULL, &tdata) != PJ_SUCCESS) { JAMI_ERR("Unable to create answer RINGING"); return PJ_FALSE; } sip_utils::addContactHeader(call->getContactHeader(), tdata); if (pjsip_inv_send_msg(call->inviteSession_.get(), tdata) != PJ_SUCCESS) { JAMI_ERR("Unable to send msg RINGING"); return PJ_FALSE; } call->setState(Call::ConnectionState::RINGING); Manager::instance().incomingCall(account->getAccountID(), *call); if (replaced_dlg) { // Get the INVITE session associated with the replaced dialog. auto replaced_inv = pjsip_dlg_get_inv_session(replaced_dlg); // Disconnect the "replaced" INVITE session. if (pjsip_inv_end_session(replaced_inv, PJSIP_SC_GONE, nullptr, &tdata) == PJ_SUCCESS && tdata) { pjsip_inv_send_msg(replaced_inv, tdata); } // Close call at application level if (auto replacedCall = getCallFromInvite(replaced_inv)) replacedCall->hangup(PJSIP_SC_OK); } return PJ_FALSE; } static void tp_state_callback(pjsip_transport* tp, pjsip_transport_state state, const pjsip_transport_state_info* info) { if (auto& broker = Manager::instance().sipVoIPLink().sipTransportBroker) broker->transportStateChanged(tp, state, info); else JAMI_ERR("SIPVoIPLink with invalid SipTransportBroker"); } /*************************************************************************************************/ pjsip_endpoint* SIPVoIPLink::getEndpoint() { return endpt_; } pjsip_module* SIPVoIPLink::getMod() { return &mod_ua_; } pj_pool_t* SIPVoIPLink::getPool() noexcept { return pool_.get(); } pj_caching_pool* SIPVoIPLink::getCachingPool() noexcept { return &cp_; } SIPVoIPLink::SIPVoIPLink() : pool_(nullptr, pj_pool_release) { #define TRY(ret) \ do { \ if ((ret) != PJ_SUCCESS) \ throw VoipLinkException(#ret " failed"); \ } while (0) pj_caching_pool_init(&cp_, &pj_pool_factory_default_policy, 0); pool_.reset(pj_pool_create(&cp_.factory, PACKAGE, 64 * 1024, 4096, nullptr)); if (!pool_) throw VoipLinkException("UserAgent: Unable to initialize memory pool"); TRY(pjsip_endpt_create(&cp_.factory, pj_gethostname()->ptr, &endpt_)); auto ns = dhtnet::ip_utils::getLocalNameservers(); if (not ns.empty()) { std::vector<pj_str_t> dns_nameservers(ns.size()); std::vector<pj_uint16_t> dns_ports(ns.size()); for (unsigned i = 0, n = ns.size(); i < n; i++) { char hbuf[NI_MAXHOST]; if (auto ret = getnameinfo((sockaddr*) &ns[i], ns[i].getLength(), hbuf, sizeof(hbuf), nullptr, 0, NI_NUMERICHOST)) { JAMI_WARN("Error printing SIP nameserver: %s", gai_strerror(ret)); } else { JAMI_DBG("Using SIP nameserver: %s", hbuf); pj_strdup2(pool_.get(), &dns_nameservers[i], hbuf); dns_ports[i] = ns[i].getPort(); } } pj_dns_resolver* resv; if (auto ret = pjsip_endpt_create_resolver(endpt_, &resv)) { JAMI_WARN("Error creating SIP DNS resolver: %s", sip_utils::sip_strerror(ret).c_str()); } else { if (auto ret = pj_dns_resolver_set_ns(resv, dns_nameservers.size(), dns_nameservers.data(), dns_ports.data())) { JAMI_WARN("Error setting SIP DNS servers: %s", sip_utils::sip_strerror(ret).c_str()); } else { if (auto ret = pjsip_endpt_set_resolver(endpt_, resv)) { JAMI_WARN("Error setting pjsip DNS resolver: %s", sip_utils::sip_strerror(ret).c_str()); } } } } sipTransportBroker.reset(new SipTransportBroker(endpt_)); auto status = pjsip_tpmgr_set_state_cb(pjsip_endpt_get_tpmgr(endpt_), tp_state_callback); if (status != PJ_SUCCESS) JAMI_ERR("Unable to set transport callback: %s", sip_utils::sip_strerror(status).c_str()); TRY(pjsip_tsx_layer_init_module(endpt_)); TRY(pjsip_ua_init_module(endpt_, nullptr)); TRY(pjsip_replaces_init_module(endpt_)); // See the Replaces specification in RFC 3891 TRY(pjsip_100rel_init_module(endpt_)); // Initialize and register ring module mod_ua_.name = sip_utils::CONST_PJ_STR(PACKAGE); mod_ua_.id = -1; mod_ua_.priority = PJSIP_MOD_PRIORITY_APPLICATION; mod_ua_.on_rx_request = &transaction_request_cb; mod_ua_.on_rx_response = &transaction_response_cb; TRY(pjsip_endpt_register_module(endpt_, &mod_ua_)); TRY(pjsip_evsub_init_module(endpt_)); TRY(pjsip_xfer_init_module(endpt_)); // presence/publish management TRY(pjsip_pres_init_module(endpt_, pjsip_evsub_instance())); TRY(pjsip_endpt_register_module(endpt_, &PresSubServer::mod_presence_server)); static const pjsip_inv_callback inv_cb = { invite_session_state_changed_cb, outgoing_request_forked_cb, transaction_state_changed_cb, nullptr /* on_rx_offer */, on_rx_offer2, reinvite_received_cb, sdp_create_offer_cb, sdp_media_update_cb, nullptr /* on_send_ack */, nullptr /* on_redirected */, }; TRY(pjsip_inv_usage_init(endpt_, &inv_cb)); static constexpr pj_str_t allowed[] = { CONST_PJ_STR(sip_utils::SIP_METHODS::INFO), CONST_PJ_STR(sip_utils::SIP_METHODS::OPTIONS), CONST_PJ_STR(sip_utils::SIP_METHODS::MESSAGE), CONST_PJ_STR(sip_utils::SIP_METHODS::PUBLISH), }; pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ALLOW, nullptr, PJ_ARRAY_SIZE(allowed), allowed); static constexpr pj_str_t text_plain = CONST_PJ_STR("text/plain"); pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, nullptr, 1, &text_plain); static constexpr pj_str_t accepted = CONST_PJ_STR("application/sdp"); pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, nullptr, 1, &accepted); static constexpr pj_str_t iscomposing = CONST_PJ_STR("application/im-iscomposing+xml"); pjsip_endpt_add_capability(endpt_, &mod_ua_, PJSIP_H_ACCEPT, nullptr, 1, &iscomposing); TRY(pjsip_replaces_init_module(endpt_)); #undef TRY sipThread_ = std::thread([this] { while (running_) handleEvents(); }); JAMI_DBG("SIPVoIPLink@%p", this); } SIPVoIPLink::~SIPVoIPLink() {} void SIPVoIPLink::shutdown() { JAMI_DBG("Shutdown SIPVoIPLink@%p...", this); // Remaining calls should not happen as possible upper callbacks // may be called and another instance of SIPVoIPLink can be re-created! if (not Manager::instance().callFactory.empty(Call::LinkType::SIP)) JAMI_ERR("%zu SIP calls remains!", Manager::instance().callFactory.callCount(Call::LinkType::SIP)); sipTransportBroker->shutdown(); pjsip_tpmgr_set_state_cb(pjsip_endpt_get_tpmgr(endpt_), nullptr); running_ = false; sipThread_.join(); pjsip_endpt_destroy(endpt_); pool_.reset(); pj_caching_pool_destroy(&cp_); sipTransportBroker.reset(); JAMI_DBG("SIPVoIPLink@%p is shutdown", this); } std::shared_ptr<SIPAccountBase> SIPVoIPLink::guessAccount(std::string_view userName, std::string_view server, std::string_view fromUri) const { JAMI_DBG("username = %.*s, server = %.*s, from = %.*s", (int) userName.size(), userName.data(), (int) server.size(), server.data(), (int) fromUri.size(), fromUri.data()); // Try to find the account id from username and server name by full match std::shared_ptr<SIPAccountBase> result; std::shared_ptr<SIPAccountBase> IP2IPAccount; MatchRank best = MatchRank::NONE; // SIP accounts for (const auto& account : Manager::instance().getAllAccounts<SIPAccount>()) { const MatchRank match(account->matches(userName, server)); // return right away if this is a full match if (match == MatchRank::FULL) { return account; } else if (match > best) { best = match; result = account; } else if (!IP2IPAccount && account->isIP2IP()) { // Allow IP2IP calls if an account exists for this type of calls IP2IPAccount = account; } } return result ? result : IP2IPAccount; } // Called from EventThread::run (not main thread) void SIPVoIPLink::handleEvents() { const pj_time_val timeout = {1, 0}; if (auto ret = pjsip_endpt_handle_events(endpt_, &timeout)) JAMI_ERR("pjsip_endpt_handle_events failed with error %s", sip_utils::sip_strerror(ret).c_str()); } void SIPVoIPLink::registerKeepAliveTimer(pj_timer_entry& timer, pj_time_val& delay) { JAMI_DEBUG("Register new keep alive timer {:d} with delay {:d}", timer.id, delay.sec); if (timer.id == -1) JAMI_WARN("Timer already scheduled"); switch (pjsip_endpt_schedule_timer(endpt_, &timer, &delay)) { case PJ_SUCCESS: break; default: JAMI_ERR("Unable to schedule new timer in pjsip endpoint"); /* fallthrough */ case PJ_EINVAL: JAMI_ERR("Invalid timer or delay entry"); break; case PJ_EINVALIDOP: JAMI_ERR("Invalid timer entry, maybe already scheduled"); break; } } void SIPVoIPLink::cancelKeepAliveTimer(pj_timer_entry& timer) { pjsip_endpt_cancel_timer(endpt_, &timer); } /////////////////////////////////////////////////////////////////////////////// // Private functions /////////////////////////////////////////////////////////////////////////////// static std::shared_ptr<SIPCall> getCallFromInvite(pjsip_inv_session* inv) { if (auto call_ptr = static_cast<SIPCall*>(inv->mod_data[mod_ua_.id])) return std::static_pointer_cast<SIPCall>(call_ptr->shared_from_this()); return nullptr; } static void invite_session_state_changed_cb(pjsip_inv_session* inv, pjsip_event* ev) { if (inv == nullptr or ev == nullptr) { throw VoipLinkException("unexpected null pointer"); } auto call = getCallFromInvite(inv); if (not call) return; if (ev->type != PJSIP_EVENT_TSX_STATE and ev->type != PJSIP_EVENT_TX_MSG and ev->type != PJSIP_EVENT_RX_MSG) { JAMI_WARN("[call:%s] INVITE@%p state changed to %d (%s): unexpected event type %d", call->getCallId().c_str(), inv, inv->state, pjsip_inv_state_name(inv->state), ev->type); return; } decltype(pjsip_transaction::status_code) status_code = 0; if (ev->type == PJSIP_EVENT_TSX_STATE) { const auto tsx = ev->body.tsx_state.tsx; status_code = tsx ? tsx->status_code : PJSIP_SC_NOT_FOUND; const pj_str_t* description = pjsip_get_status_text(status_code); JAMI_DBG("[call:%s] INVITE@%p state changed to %d (%s): cause=%d, tsx@%p status %d (%.*s)", call->getCallId().c_str(), inv, inv->state, pjsip_inv_state_name(inv->state), inv->cause, tsx, status_code, (int) description->slen, description->ptr); } else if (ev->type == PJSIP_EVENT_TX_MSG) { JAMI_DBG("[call:%s] INVITE@%p state changed to %d (%s): cause=%d (TX_MSG)", call->getCallId().c_str(), inv, inv->state, pjsip_inv_state_name(inv->state), inv->cause); } pjsip_rx_data* rdata {nullptr}; if (ev->type == PJSIP_EVENT_RX_MSG) { rdata = ev->body.rx_msg.rdata; } else if (ev->type == PJSIP_EVENT_TSX_STATE and ev->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { rdata = ev->body.tsx_state.src.rdata; } if (rdata != nullptr) { call->setPeerUaVersion(sip_utils::getPeerUserAgent(rdata)); auto methods = sip_utils::getPeerAllowMethods(rdata); if (not methods.empty()) { call->setPeerAllowMethods(std::move(methods)); } } switch (inv->state) { case PJSIP_INV_STATE_EARLY: if (status_code == PJSIP_SC_RINGING) call->onPeerRinging(); break; case PJSIP_INV_STATE_CONFIRMED: // After we sent or received a ACK - The connection is established call->onAnswered(); break; case PJSIP_INV_STATE_DISCONNECTED: switch (inv->cause) { // When a peer's device replies busy case PJSIP_SC_BUSY_HERE: call->onBusyHere(); break; // When the peer manually refuse the call case PJSIP_SC_DECLINE: case PJSIP_SC_BUSY_EVERYWHERE: if (inv->role != PJSIP_ROLE_UAC) break; // close call call->onClosed(); break; // The call terminates normally - BYE / CANCEL case PJSIP_SC_OK: case PJSIP_SC_REQUEST_TERMINATED: call->onClosed(); break; // Error/unhandled conditions default: call->onFailure(inv->cause); break; } break; default: break; } } static void on_rx_offer2(pjsip_inv_session* inv, struct pjsip_inv_on_rx_offer_cb_param* param) { if (not param or not param->offer) { JAMI_ERR("Invalid offer"); return; } auto call = getCallFromInvite(inv); if (not call) return; // This callback is called whenever a new media offer is found in a // SIP message, typically in a re-invite and in a '200 OK' (as a // response to an empty invite). // Here we only handle the second case. The first case is handled // in reinvite_received_cb. if (inv->cause != PJSIP_SC_OK) { // Silently ignore if it's not a '200 OK' return; } if (auto call = getCallFromInvite(inv)) { if (auto const& account = call->getAccount().lock()) { call->onReceiveOfferIn200OK(param->offer); } } } static pj_status_t reinvite_received_cb(pjsip_inv_session* inv, const pjmedia_sdp_session* offer, pjsip_rx_data* rdata) { if (!offer) return !PJ_SUCCESS; if (auto call = getCallFromInvite(inv)) { if (auto const& account = call->getAccount().lock()) { return call->onReceiveReinvite(offer, rdata); } } // Return success if there is no matching call. The re-invite // should be ignored. return PJ_SUCCESS; } static void sdp_create_offer_cb(pjsip_inv_session* inv, pjmedia_sdp_session** p_offer) { auto call = getCallFromInvite(inv); if (not call) return; auto account = call->getSIPAccount(); if (not account) { JAMI_ERR("No account detected"); return; } if (account->isEmptyOffersEnabled()) { // Skip if the client wants to send an empty offer. JAMI_DBG("Client requested to send an empty offer (no SDP)"); return; } auto family = pj_AF_INET(); // FIXME : for now, use the same address family as the SIP transport if (auto dlg = inv->dlg) { if (dlg->tp_sel.type == PJSIP_TPSELECTOR_TRANSPORT) { if (auto tr = dlg->tp_sel.u.transport) family = tr->local_addr.addr.sa_family; } else if (dlg->tp_sel.type == PJSIP_TPSELECTOR_TRANSPORT) { if (auto tr = dlg->tp_sel.u.listener) family = tr->local_addr.addr.sa_family; } } auto ifaceAddr = dhtnet::ip_utils::getInterfaceAddr(account->getLocalInterface(), family); dhtnet::IpAddr address; if (account->getUPnPActive()) { /* use UPnP addr, or published addr if its set */ address = account->getPublishedSameasLocal() ? account->getUPnPIpAddress() : account->getPublishedIpAddress(); } else { address = account->getPublishedSameasLocal() ? ifaceAddr : account->getPublishedIpAddress(); } /* fallback on local address */ if (not address) address = ifaceAddr; auto& sdp = call->getSDP(); sdp.setPublishedIP(address); // This list should be provided by the client. Kept for backward compatibility. auto const& mediaList = call->getMediaAttributeList(); if (mediaList.empty()) { throw VoipLinkException("Unexpected empty media attribute list"); } JAMI_DBG("Creating a SDP offer using the following media:"); for (auto const& media : mediaList) { JAMI_DBG("[call %s] Media %s", call->getCallId().c_str(), media.toString(true).c_str()); } const bool created = sdp.createOffer(mediaList); if (created and p_offer != nullptr) *p_offer = sdp.getLocalSdpSession(); } static const pjmedia_sdp_session* get_active_remote_sdp(pjsip_inv_session* inv) { const pjmedia_sdp_session* sdp_session {}; if (pjmedia_sdp_neg_get_active_remote(inv->neg, &sdp_session) != PJ_SUCCESS) { JAMI_ERR("Active remote not present"); return nullptr; } if (pjmedia_sdp_validate(sdp_session) != PJ_SUCCESS) { JAMI_ERR("Invalid remote SDP session"); return nullptr; } return sdp_session; } static const pjmedia_sdp_session* get_active_local_sdp(pjsip_inv_session* inv) { const pjmedia_sdp_session* sdp_session {}; if (pjmedia_sdp_neg_get_active_local(inv->neg, &sdp_session) != PJ_SUCCESS) { JAMI_ERR("Active local not present"); return nullptr; } if (pjmedia_sdp_validate(sdp_session) != PJ_SUCCESS) { JAMI_ERR("Invalid local SDP session"); return nullptr; } return sdp_session; } // This callback is called after SDP offer/answer session has completed. static void sdp_media_update_cb(pjsip_inv_session* inv, pj_status_t status) { auto call = getCallFromInvite(inv); if (not call) return; JAMI_DBG("[call:%s] INVITE@%p media update: status %d", call->getCallId().c_str(), inv, status); if (status != PJ_SUCCESS) { const int reason = inv->state != PJSIP_INV_STATE_NULL and inv->state != PJSIP_INV_STATE_CONFIRMED ? PJSIP_SC_UNSUPPORTED_MEDIA_TYPE : 0; JAMI_WARN("[call:%s] SDP offer failed, reason %d", call->getCallId().c_str(), reason); call->hangup(reason); return; } // Fetch SDP data from request const auto localSDP = get_active_local_sdp(inv); const auto remoteSDP = get_active_remote_sdp(inv); // Update our SDP manager auto& sdp = call->getSDP(); sdp.setActiveLocalSdpSession(localSDP); if (localSDP != nullptr) { Sdp::printSession(localSDP, "Local active session:", sdp.getSdpDirection()); } sdp.setActiveRemoteSdpSession(remoteSDP); if (remoteSDP != nullptr) { Sdp::printSession(remoteSDP, "Remote active session:", sdp.getSdpDirection()); } call->onMediaNegotiationComplete(); } static void outgoing_request_forked_cb(pjsip_inv_session* /*inv*/, pjsip_event* /*e*/) {} static bool handleMediaControl(SIPCall& call, pjsip_msg_body* body) { /* * Incoming INFO request for media control. */ constexpr pj_str_t STR_APPLICATION = CONST_PJ_STR("application"); constexpr pj_str_t STR_MEDIA_CONTROL_XML = CONST_PJ_STR("media_control+xml"); if (body->len and pj_stricmp(&body->content_type.type, &STR_APPLICATION) == 0 and pj_stricmp(&body->content_type.subtype, &STR_MEDIA_CONTROL_XML) == 0) { auto body_msg = std::string_view((char*) body->data, (size_t) body->len); /* Apply and answer the INFO request */ static constexpr auto PICT_FAST_UPDATE = "picture_fast_update"sv; static constexpr auto STREAM_ID = "stream_id"sv; static constexpr auto DEVICE_ORIENTATION = "device_orientation"sv; static constexpr auto RECORDING_STATE = "recording_state"sv; static constexpr auto MUTE_STATE = "mute_state"sv; static constexpr auto VOICE_ACTIVITY = "voice_activity"sv; int streamIdx = -1; if (body_msg.find(STREAM_ID) != std::string_view::npos) { // Note: here we use the index of the RTP stream, not it's label! // Indeed, both side will have different labels as they have different call ids static const std::regex STREAMID_REGEX("<stream_id>([0-9]+)</stream_id>"); std::svmatch matched_pattern; std::regex_search(body_msg, matched_pattern, STREAMID_REGEX); if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { try { streamIdx = std::stoi(matched_pattern[1]); } catch (const std::exception& e) { JAMI_WARN("Error parsing stream index: %s", e.what()); } } } if (body_msg.find(PICT_FAST_UPDATE) != std::string_view::npos) { call.sendKeyframe(streamIdx); return true; } else if (body_msg.find(DEVICE_ORIENTATION) != std::string_view::npos) { static const std::regex ORIENTATION_REGEX("device_orientation=([-+]?[0-9]+)"); std::svmatch matched_pattern; std::regex_search(body_msg, matched_pattern, ORIENTATION_REGEX); if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { try { int rotation = -std::stoi(matched_pattern[1]); while (rotation <= -180) rotation += 360; while (rotation > 180) rotation -= 360; JAMI_WARN("Rotate video %d deg.", rotation); #ifdef ENABLE_VIDEO call.setRotation(streamIdx, rotation); #endif } catch (const std::exception& e) { JAMI_WARN("Error parsing angle: %s", e.what()); } return true; } } else if (body_msg.find(RECORDING_STATE) != std::string_view::npos) { static const std::regex REC_REGEX("recording_state=([0-1])"); std::svmatch matched_pattern; std::regex_search(body_msg, matched_pattern, REC_REGEX); if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { try { bool state = std::stoi(matched_pattern[1]); call.peerRecording(state); } catch (const std::exception& e) { JAMI_WARN("Error parsing state remote recording: %s", e.what()); } return true; } } else if (body_msg.find(MUTE_STATE) != std::string_view::npos) { static const std::regex REC_REGEX("mute_state=([0-1])"); std::svmatch matched_pattern; std::regex_search(body_msg, matched_pattern, REC_REGEX); if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { try { bool state = std::stoi(matched_pattern[1]); call.peerMuted(state, streamIdx); } catch (const std::exception& e) { JAMI_WARN("Error parsing state remote mute: %s", e.what()); } return true; } } else if (body_msg.find(VOICE_ACTIVITY) != std::string_view::npos) { static const std::regex REC_REGEX("voice_activity=([0-1])"); std::svmatch matched_pattern; std::regex_search(body_msg, matched_pattern, REC_REGEX); if (matched_pattern.ready() && !matched_pattern.empty() && matched_pattern[1].matched) { try { bool state = std::stoi(matched_pattern[1]); call.peerVoice(state); } catch (const std::exception& e) { JAMI_WARN("Error parsing state remote voice: %s", e.what()); } return true; } } } return false; } /** * Helper function to process refer function on call transfer */ static bool transferCall(SIPCall& call, const std::string& refer_to) { const auto& callId = call.getCallId(); JAMI_WARN("[call:%s] Attempting to transfer to %s", callId.c_str(), refer_to.c_str()); try { Manager::instance().newOutgoingCall(refer_to, call.getAccountId(), MediaAttribute::mediaAttributesToMediaMaps( call.getMediaAttributeList())); Manager::instance().hangupCall(call.getAccountId(), callId); } catch (const std::exception& e) { JAMI_ERR("[call:%s] SIP transfer failed: %s", callId.c_str(), e.what()); return false; } return true; } static void replyToRequest(pjsip_inv_session* inv, pjsip_rx_data* rdata, int status_code) { const auto ret = pjsip_dlg_respond(inv->dlg, rdata, status_code, nullptr, nullptr, nullptr); if (ret != PJ_SUCCESS) JAMI_WARN("SIP: Failed to reply %d to request", status_code); } static void onRequestRefer(pjsip_inv_session* inv, pjsip_rx_data* rdata, pjsip_msg* msg, SIPCall& call) { static constexpr pj_str_t str_refer_to = CONST_PJ_STR("Refer-To"); if (auto refer_to = static_cast<pjsip_generic_string_hdr*>( pjsip_msg_find_hdr_by_name(msg, &str_refer_to, nullptr))) { // RFC 3515, 2.4.2: reply bad request if no or too many refer-to header. if (static_cast<void*>(refer_to->next) == static_cast<void*>(&msg->hdr) or !pjsip_msg_find_hdr_by_name(msg, &str_refer_to, refer_to->next)) { replyToRequest(inv, rdata, PJSIP_SC_ACCEPTED); transferCall(call, std::string(refer_to->hvalue.ptr, refer_to->hvalue.slen)); // RFC 3515, 2.4.4: we MUST handle the processing using NOTIFY msgs // But your current design doesn't permit that return; } else JAMI_ERR("[call:%s] REFER: too many Refer-To headers", call.getCallId().c_str()); } else JAMI_ERR("[call:%s] REFER: no Refer-To header", call.getCallId().c_str()); replyToRequest(inv, rdata, PJSIP_SC_BAD_REQUEST); } static void onRequestInfo(pjsip_inv_session* inv, pjsip_rx_data* rdata, pjsip_msg* msg, SIPCall& call) { if (!msg->body or handleMediaControl(call, msg->body)) replyToRequest(inv, rdata, PJSIP_SC_OK); } static void onRequestNotify(pjsip_inv_session* /*inv*/, pjsip_rx_data* /*rdata*/, pjsip_msg* msg, SIPCall& call) { if (!msg->body) return; const std::string bodyText {static_cast<char*>(msg->body->data), msg->body->len}; JAMI_DBG("[call:%s] NOTIFY body start - %p\n%s\n[call:%s] NOTIFY body end - %p", call.getCallId().c_str(), msg->body, bodyText.c_str(), call.getCallId().c_str(), msg->body); // TODO } static void transaction_state_changed_cb(pjsip_inv_session* inv, pjsip_transaction* tsx, pjsip_event* event) { auto call = getCallFromInvite(inv); if (not call) return; #ifdef DEBUG_SIP_REQUEST_MSG processInviteResponseHelper(inv, event); #endif // We process here only incoming request message if (tsx->role != PJSIP_ROLE_UAS or tsx->state != PJSIP_TSX_STATE_TRYING or event->body.tsx_state.type != PJSIP_EVENT_RX_MSG) { return; } const auto rdata = event->body.tsx_state.src.rdata; if (!rdata) { JAMI_ERR("[INVITE:%p] SIP RX request without rx data", inv); return; } const auto msg = rdata->msg_info.msg; if (msg->type != PJSIP_REQUEST_MSG) { JAMI_ERR("[INVITE:%p] SIP RX request without msg", inv); return; } // Using method name to dispatch auto methodName = sip_utils::as_view(msg->line.req.method.name); JAMI_DBG("[INVITE:%p] RX SIP method %d (%.*s)", inv, msg->line.req.method.id, (int) methodName.size(), methodName.data()); #ifdef DEBUG_SIP_REQUEST_MSG char msgbuf[1000]; pjsip_msg_print(msg, msgbuf, sizeof msgbuf); JAMI_DBG("%s", msgbuf); #endif // DEBUG_SIP_MESSAGE if (methodName == sip_utils::SIP_METHODS::REFER) onRequestRefer(inv, rdata, msg, *call); else if (methodName == sip_utils::SIP_METHODS::INFO) onRequestInfo(inv, rdata, msg, *call); else if (methodName == sip_utils::SIP_METHODS::NOTIFY) onRequestNotify(inv, rdata, msg, *call); else if (methodName == sip_utils::SIP_METHODS::OPTIONS) handleIncomingOptions(rdata); else if (methodName == sip_utils::SIP_METHODS::MESSAGE) { if (msg->body) runOnMainThread([call, m = im::parseSipMessage(msg)]() mutable { call->onTextMessage(std::move(m)); }); } } #ifdef DEBUG_SIP_REQUEST_MSG static void processInviteResponseHelper(pjsip_inv_session* inv, pjsip_event* event) { if (event->body.tsx_state.type != PJSIP_EVENT_RX_MSG) return; const auto rdata = event->body.tsx_state.src.rdata; if (rdata == nullptr or rdata->msg_info.msg == nullptr) return; const auto msg = rdata->msg_info.msg; if (msg->type != PJSIP_RESPONSE_MSG) return; // Only handle the following responses switch (msg->line.status.code) { case PJSIP_SC_TRYING: case PJSIP_SC_RINGING: case PJSIP_SC_OK: break; default: return; } JAMI_INFO("[INVITE:%p] SIP RX response: reason %.*s, status code %i", inv, (int) msg->line.status.reason.slen, msg->line.status.reason.ptr, msg->line.status.code); sip_utils::logMessageHeaders(&msg->hdr); } #endif int SIPVoIPLink::getModId() { return mod_ua_.id; } void SIPVoIPLink::createSDPOffer(pjsip_inv_session* inv) { if (inv == nullptr) { throw VoipLinkException("Invite session is unable to be null"); } sdp_create_offer_cb(inv, nullptr); } // Thread-safe DNS resolver callback mapping class SafeResolveCallbackMap { public: using ResolveCallback = std::function<void(pj_status_t, const pjsip_server_addresses*)>; void registerCallback(uintptr_t key, ResolveCallback&& cb) { std::lock_guard lk(mutex_); cbMap_.emplace(key, std::move(cb)); } void process(uintptr_t key, pj_status_t status, const pjsip_server_addresses* addr) { std::lock_guard lk(mutex_); auto it = cbMap_.find(key); if (it != cbMap_.end()) { it->second(status, addr); cbMap_.erase(it); } } private: std::mutex mutex_; std::map<uintptr_t, ResolveCallback> cbMap_; }; static SafeResolveCallbackMap& getResolveCallbackMap() { static SafeResolveCallbackMap map; return map; } static void resolver_callback(pj_status_t status, void* token, const struct pjsip_server_addresses* addr) { getResolveCallbackMap().process((uintptr_t) token, status, addr); } void SIPVoIPLink::resolveSrvName(const std::string& name, pjsip_transport_type_e type, SrvResolveCallback&& cb) { // PJSIP limits hostname to be longer than PJ_MAX_HOSTNAME. // But, resolver prefix the given name by a string like "_sip._udp." // causing a check against PJ_MAX_HOSTNAME to be useless. // It's not easy to pre-determinate as it's implementation dependent. // So we just choose a security marge enough for most cases, preventing a crash later // in the call of pjsip_endpt_resolve(). if (name.length() > (PJ_MAX_HOSTNAME - 12)) { JAMI_ERR("Hostname is too long"); cb({}); return; } // extract port if name is in form "server:port" int port; pj_ssize_t name_size; const auto n = name.rfind(':'); if (n != std::string::npos) { port = std::atoi(name.c_str() + n + 1); name_size = n; } else { port = 0; name_size = name.size(); } JAMI_DBG("try to resolve '%s' (port: %u)", name.c_str(), port); pjsip_host_info host_info { /*.flag = */ 0, /*.type = */ type, /*.addr = */ {{(char*) name.c_str(), name_size}, port}, }; const auto token = std::hash<std::string>()(name + std::to_string(type)); getResolveCallbackMap().registerCallback( token, [=, cb = std::move(cb)](pj_status_t s, const pjsip_server_addresses* r) { try { if (s != PJ_SUCCESS || !r) { JAMI_WARN("Unable to resolve \"%s\" using pjsip_endpt_resolve, trying getaddrinfo.", name.c_str()); dht::ThreadPool::io().run([=, cb = std::move(cb)]() { auto ips = dhtnet::ip_utils::getAddrList(name.c_str()); runOnMainThread(std::bind(cb, std::move(ips))); }); } else { std::vector<dhtnet::IpAddr> ips; ips.reserve(r->count); for (unsigned i = 0; i < r->count; i++) ips.push_back(r->entry[i].addr); cb(ips); } } catch (const std::exception& e) { JAMI_ERR("Error resolving address: %s", e.what()); cb({}); } }); pjsip_endpt_resolve(endpt_, pool_.get(), &host_info, (void*) token, resolver_callback); } #define RETURN_IF_NULL(A, ...) \ if ((A) == NULL) { \ JAMI_WARN(__VA_ARGS__); \ return; \ } #define RETURN_FALSE_IF_NULL(A, ...) \ if ((A) == NULL) { \ JAMI_WARN(__VA_ARGS__); \ return false; \ } void SIPVoIPLink::findLocalAddressFromTransport(pjsip_transport* transport, pjsip_transport_type_e transportType, const std::string& host, std::string& addr, pj_uint16_t& port) const { // Initialize the sip port with the default SIP port port = pjsip_transport_get_default_port_for_type(transportType); // Initialize the sip address with the hostname addr = sip_utils::as_view(*pj_gethostname()); // Update address and port with active transport RETURN_IF_NULL(transport, "Transport is NULL in findLocalAddress, using local address %s :%d", addr.c_str(), port); // get the transport manager associated with the SIP enpoint auto tpmgr = pjsip_endpt_get_tpmgr(endpt_); RETURN_IF_NULL(tpmgr, "Transport manager is NULL in findLocalAddress, using local address %s :%d", addr.c_str(), port); const pj_str_t pjstring(CONST_PJ_STR(host)); auto tp_sel = getTransportSelector(transport); pjsip_tpmgr_fla2_param param = {transportType, &tp_sel, pjstring, PJ_FALSE, {nullptr, 0}, 0, nullptr}; if (pjsip_tpmgr_find_local_addr2(tpmgr, pool_.get(), &param) != PJ_SUCCESS) { JAMI_WARN("Unable to retrieve local address and port from transport, using %s :%d", addr.c_str(), port); return; } // Update local address based on the transport type addr = sip_utils::as_view(param.ret_addr); // Determine the local port based on transport information port = param.ret_port; } bool SIPVoIPLink::findLocalAddressFromSTUN(pjsip_transport* transport, pj_str_t* stunServerName, int stunPort, std::string& addr, pj_uint16_t& port) const { // WARN: this code use pjstun_get_mapped_addr2 that works // in IPv4 only. // WARN: this function is blocking (network request). // Initialize the sip port with the default SIP port port = sip_utils::DEFAULT_SIP_PORT; // Get Local IP address auto localIp = dhtnet::ip_utils::getLocalAddr(pj_AF_INET()); if (not localIp) { JAMI_WARN("Failed to find local IP"); return false; } addr = localIp.toString(); // Update address and port with active transport RETURN_FALSE_IF_NULL(transport, "Transport is NULL in findLocalAddress, using local address %s:%u", addr.c_str(), port); JAMI_DBG("STUN mapping of '%s:%u'", addr.c_str(), port); pj_sockaddr_in mapped_addr; pj_sock_t sipSocket = pjsip_udp_transport_get_socket(transport); const pjstun_setting stunOpt = {PJ_TRUE, localIp.getFamily(), *stunServerName, stunPort, *stunServerName, stunPort}; pj_status_t stunStatus = pjstun_get_mapped_addr2(&cp_.factory, &stunOpt, 1, &sipSocket, &mapped_addr); switch (stunStatus) { case PJLIB_UTIL_ESTUNNOTRESPOND: JAMI_ERROR("No response from STUN server {:s}", sip_utils::as_view(*stunServerName)); return false; case PJLIB_UTIL_ESTUNSYMMETRIC: JAMI_ERR("Different mapped addresses are returned by servers."); return false; case PJ_SUCCESS: port = pj_sockaddr_in_get_port(&mapped_addr); addr = dhtnet::IpAddr((const sockaddr_in&) mapped_addr).toString(true); JAMI_DEBUG("STUN server {:s} replied '{}'", sip_utils::as_view(*stunServerName), addr); return true; default: // use given address, silent any not handled error JAMI_WARNING("Error from STUN server {:s}, using source address", sip_utils::as_view(*stunServerName)); return false; } } #undef RETURN_IF_NULL #undef RETURN_FALSE_IF_NULL } // namespace jami
59,600
C++
.cpp
1,418
32.566291
104
0.589801
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,840
sipaccount_config.cpp
savoirfairelinux_jami-daemon/src/sip/sipaccount_config.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "sipaccount_config.h" #include "account_const.h" #include "account_schema.h" #include "config/yamlparser.h" extern "C" { #include <pjlib-util/md5.h> } namespace jami { namespace Conf { constexpr const char* ID_KEY = "id"; constexpr const char* USERNAME_KEY = "username"; constexpr const char* BIND_ADDRESS_KEY = "bindAddress"; constexpr const char* INTERFACE_KEY = "interface"; constexpr const char* PORT_KEY = "port"; constexpr const char* PUBLISH_ADDR_KEY = "publishAddr"; constexpr const char* PUBLISH_PORT_KEY = "publishPort"; constexpr const char* SAME_AS_LOCAL_KEY = "sameasLocal"; constexpr const char* DTMF_TYPE_KEY = "dtmfType"; constexpr const char* SERVICE_ROUTE_KEY = "serviceRoute"; constexpr const char* ALLOW_IP_AUTO_REWRITE = "allowIPAutoRewrite"; constexpr const char* PRESENCE_ENABLED_KEY = "presenceEnabled"; constexpr const char* PRESENCE_PUBLISH_SUPPORTED_KEY = "presencePublishSupported"; constexpr const char* PRESENCE_SUBSCRIBE_SUPPORTED_KEY = "presenceSubscribeSupported"; constexpr const char* PRESENCE_STATUS_KEY = "presenceStatus"; constexpr const char* PRESENCE_NOTE_KEY = "presenceNote"; constexpr const char* PRESENCE_MODULE_ENABLED_KEY = "presenceModuleEnabled"; constexpr const char* KEEP_ALIVE_ENABLED = "keepAliveEnabled"; constexpr const char* const TLS_KEY = "tls"; constexpr const char* CERTIFICATE_KEY = "certificate"; constexpr const char* CALIST_KEY = "calist"; constexpr const char* TLS_PORT_KEY = "tlsPort"; constexpr const char* CIPHERS_KEY = "ciphers"; constexpr const char* TLS_ENABLE_KEY = "enable"; constexpr const char* METHOD_KEY = "method"; constexpr const char* TIMEOUT_KEY = "timeout"; constexpr const char* TLS_PASSWORD_KEY = "password"; constexpr const char* PRIVATE_KEY_KEY = "privateKey"; constexpr const char* REQUIRE_CERTIF_KEY = "requireCertif"; constexpr const char* SERVER_KEY = "server"; constexpr const char* VERIFY_CLIENT_KEY = "verifyClient"; constexpr const char* VERIFY_SERVER_KEY = "verifyServer"; constexpr const char* DISABLE_SECURE_DLG_CHECK = "disableSecureDlgCheck"; constexpr const char* STUN_ENABLED_KEY = "stunEnabled"; constexpr const char* STUN_SERVER_KEY = "stunServer"; constexpr const char* CRED_KEY = "credential"; constexpr const char* SRTP_KEY = "srtp"; constexpr const char* KEY_EXCHANGE_KEY = "keyExchange"; constexpr const char* RTP_FALLBACK_KEY = "rtpFallback"; } // namespace Conf static const SipAccountConfig DEFAULT_CONFIG {}; static constexpr unsigned MIN_REGISTRATION_TIME = 60; // seconds using yaml_utils::parseValueOptional; using yaml_utils::parseVectorMap; void SipAccountConfig::serialize(YAML::Emitter& out) const { out << YAML::BeginMap; out << YAML::Key << Conf::ID_KEY << YAML::Value << id; SipAccountBaseConfig::serializeDiff(out, DEFAULT_CONFIG); out << YAML::Key << Conf::BIND_ADDRESS_KEY << YAML::Value << bindAddress; out << YAML::Key << Conf::PORT_KEY << YAML::Value << localPort; out << YAML::Key << Conf::PUBLISH_PORT_KEY << YAML::Value << publishedPort; out << YAML::Key << Conf::USERNAME_KEY << YAML::Value << username; // each credential is a map, and we can have multiple credentials out << YAML::Key << Conf::CRED_KEY << YAML::Value << getCredentials(); out << YAML::Key << Conf::KEEP_ALIVE_ENABLED << YAML::Value << registrationRefreshEnabled; //out << YAML::Key << PRESENCE_MODULE_ENABLED_KEY << YAML::Value // << (presence_ and presence_->isEnabled()); out << YAML::Key << Conf::CONFIG_ACCOUNT_REGISTRATION_EXPIRE << YAML::Value << registrationExpire; out << YAML::Key << Conf::SERVICE_ROUTE_KEY << YAML::Value << serviceRoute; out << YAML::Key << Conf::ALLOW_IP_AUTO_REWRITE << YAML::Value << allowIPAutoRewrite; out << YAML::Key << Conf::STUN_ENABLED_KEY << YAML::Value << stunEnabled; out << YAML::Key << Conf::STUN_SERVER_KEY << YAML::Value << stunServer; // tls submap out << YAML::Key << Conf::TLS_KEY << YAML::Value << YAML::BeginMap; out << YAML::Key << Conf::CALIST_KEY << YAML::Value << tlsCaListFile; out << YAML::Key << Conf::CERTIFICATE_KEY << YAML::Value << tlsCertificateFile; out << YAML::Key << Conf::TLS_PASSWORD_KEY << YAML::Value << tlsPassword; out << YAML::Key << Conf::PRIVATE_KEY_KEY << YAML::Value << tlsPrivateKeyFile; out << YAML::Key << Conf::TLS_ENABLE_KEY << YAML::Value << tlsEnable; out << YAML::Key << Conf::TLS_PORT_KEY << YAML::Value << tlsListenerPort; out << YAML::Key << Conf::VERIFY_CLIENT_KEY << YAML::Value << tlsVerifyClient; out << YAML::Key << Conf::VERIFY_SERVER_KEY << YAML::Value << tlsVerifyServer; out << YAML::Key << Conf::REQUIRE_CERTIF_KEY << YAML::Value << tlsRequireClientCertificate; out << YAML::Key << Conf::DISABLE_SECURE_DLG_CHECK << YAML::Value << tlsDisableSecureDlgCheck; out << YAML::Key << Conf::TIMEOUT_KEY << YAML::Value << tlsNegotiationTimeout; out << YAML::Key << Conf::CIPHERS_KEY << YAML::Value << tlsCiphers; out << YAML::Key << Conf::METHOD_KEY << YAML::Value << tlsMethod; out << YAML::Key << Conf::SERVER_KEY << YAML::Value << tlsServerName; out << YAML::EndMap; // srtp submap out << YAML::Key << Conf::SRTP_KEY << YAML::Value << YAML::BeginMap; out << YAML::Key << Conf::KEY_EXCHANGE_KEY << YAML::Value << sip_utils::getKeyExchangeName(srtpKeyExchange); out << YAML::Key << Conf::RTP_FALLBACK_KEY << YAML::Value << srtpFallback; out << YAML::EndMap; out << YAML::EndMap; } void SipAccountConfig::unserialize(const YAML::Node& node) { SipAccountBaseConfig::unserialize(node); parseValueOptional(node, Conf::USERNAME_KEY, username); parseValueOptional(node, Conf::BIND_ADDRESS_KEY, bindAddress); parseValueOptional(node, Conf::PORT_KEY, localPort); parseValueOptional(node, Conf::PUBLISH_PORT_KEY, publishedPort); parseValueOptional(node, Conf::CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire); registrationExpire = std::max(MIN_REGISTRATION_TIME, registrationExpire); parseValueOptional(node, Conf::KEEP_ALIVE_ENABLED, registrationRefreshEnabled); parseValueOptional(node, Conf::SERVICE_ROUTE_KEY, serviceRoute); parseValueOptional(node, Conf::ALLOW_IP_AUTO_REWRITE, allowIPAutoRewrite); parseValueOptional(node, Conf::PRESENCE_MODULE_ENABLED_KEY, presenceEnabled); parseValueOptional(node, Conf::PRESENCE_PUBLISH_SUPPORTED_KEY, publishSupported); parseValueOptional(node, Conf::PRESENCE_SUBSCRIBE_SUPPORTED_KEY, subscribeSupported); // ICE - STUN/TURN parseValueOptional(node, Conf::STUN_ENABLED_KEY, stunEnabled); parseValueOptional(node, Conf::STUN_SERVER_KEY, stunServer); const auto& credsNode = node[Conf::CRED_KEY]; setCredentials(parseVectorMap(credsNode, {Conf::CONFIG_ACCOUNT_REALM, Conf::CONFIG_ACCOUNT_USERNAME, Conf::CONFIG_ACCOUNT_PASSWORD})); // get tls submap try { const auto& tlsMap = node[Conf::TLS_KEY]; parseValueOptional(tlsMap, Conf::CERTIFICATE_KEY, tlsCertificateFile); parseValueOptional(tlsMap, Conf::CALIST_KEY, tlsCaListFile); parseValueOptional(tlsMap, Conf::TLS_PASSWORD_KEY, tlsPassword); parseValueOptional(tlsMap, Conf::PRIVATE_KEY_KEY, tlsPrivateKeyFile); parseValueOptional(tlsMap, Conf::TLS_ENABLE_KEY, tlsEnable); parseValueOptional(tlsMap, Conf::TLS_PORT_KEY, tlsListenerPort); parseValueOptional(tlsMap, Conf::CIPHERS_KEY, tlsCiphers); parseValueOptional(tlsMap, Conf::METHOD_KEY, tlsMethod); parseValueOptional(tlsMap, Conf::SERVER_KEY, tlsServerName); parseValueOptional(tlsMap, Conf::REQUIRE_CERTIF_KEY, tlsRequireClientCertificate); parseValueOptional(tlsMap, Conf::VERIFY_CLIENT_KEY, tlsVerifyClient); parseValueOptional(tlsMap, Conf::VERIFY_SERVER_KEY, tlsVerifyServer); parseValueOptional(tlsMap, Conf::DISABLE_SECURE_DLG_CHECK, tlsDisableSecureDlgCheck); parseValueOptional(tlsMap, Conf::TIMEOUT_KEY, tlsNegotiationTimeout); } catch (...) {} // get srtp submap const auto& srtpMap = node[Conf::SRTP_KEY]; std::string tmpKey; parseValueOptional(srtpMap, Conf::KEY_EXCHANGE_KEY, tmpKey); srtpKeyExchange = sip_utils::getKeyExchangeProtocol(tmpKey); parseValueOptional(srtpMap, Conf::RTP_FALLBACK_KEY, srtpFallback); } std::map<std::string, std::string> SipAccountConfig::toMap() const { auto a = SipAccountBaseConfig::toMap(); // general sip settings a.emplace(Conf::CONFIG_ACCOUNT_USERNAME, username); a.emplace(Conf::CONFIG_LOCAL_PORT, std::to_string(localPort)); a.emplace(Conf::CONFIG_ACCOUNT_DTMF_TYPE, dtmfType); a.emplace(Conf::CONFIG_LOCAL_INTERFACE, interface); a.emplace(Conf::CONFIG_PUBLISHED_PORT, std::to_string(publishedPort)); a.emplace(Conf::CONFIG_PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_PUBLISHED_ADDRESS, publishedIp); a.emplace(Conf::CONFIG_STUN_ENABLE, stunEnabled ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_STUN_SERVER, stunServer); a.emplace(Conf::CONFIG_BIND_ADDRESS, bindAddress); a.emplace(Conf::CONFIG_ACCOUNT_ROUTESET, serviceRoute); a.emplace(Conf::CONFIG_ACCOUNT_IP_AUTO_REWRITE, allowIPAutoRewrite ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_PRESENCE_ENABLED, presenceEnabled ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_KEEP_ALIVE_ENABLED, registrationRefreshEnabled ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_ACCOUNT_REGISTRATION_EXPIRE, std::to_string(registrationExpire)); std::string password {}; if (not credentials.empty()) { for (const auto& cred : credentials) if (cred.username == username) { password = cred.password; break; } } a.emplace(Conf::CONFIG_ACCOUNT_PASSWORD, std::move(password)); // srtp settings a.emplace(Conf::CONFIG_SRTP_KEY_EXCHANGE, sip_utils::getKeyExchangeName(srtpKeyExchange)); a.emplace(Conf::CONFIG_SRTP_RTP_FALLBACK, srtpFallback ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TLS_ENABLE, tlsEnable ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TLS_LISTENER_PORT, std::to_string(tlsListenerPort)); a.emplace(Conf::CONFIG_TLS_CA_LIST_FILE, tlsCaListFile); a.emplace(Conf::CONFIG_TLS_CERTIFICATE_FILE, tlsCertificateFile); a.emplace(Conf::CONFIG_TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile); a.emplace(Conf::CONFIG_TLS_PASSWORD, tlsPassword); a.emplace(Conf::CONFIG_TLS_METHOD, tlsMethod); a.emplace(Conf::CONFIG_TLS_CIPHERS, tlsCiphers); a.emplace(Conf::CONFIG_TLS_SERVER_NAME, tlsServerName); a.emplace(Conf::CONFIG_TLS_VERIFY_SERVER, tlsVerifyServer ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TLS_VERIFY_CLIENT, tlsVerifyClient ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate ? TRUE_STR : FALSE_STR); a.emplace(Conf::CONFIG_TLS_NEGOTIATION_TIMEOUT_SEC, std::to_string(tlsNegotiationTimeout)); a.emplace(Conf::CONFIG_TLS_DISABLE_SECURE_DLG_CHECK, tlsDisableSecureDlgCheck ? TRUE_STR : FALSE_STR); return a; } void SipAccountConfig::fromMap(const std::map<std::string, std::string>& details) { SipAccountBaseConfig::fromMap(details); // general sip settings parseString(details, Conf::CONFIG_ACCOUNT_USERNAME, username); parseInt(details, Conf::CONFIG_LOCAL_PORT, localPort); parseString(details, Conf::CONFIG_BIND_ADDRESS, bindAddress); parseString(details, Conf::CONFIG_ACCOUNT_ROUTESET, serviceRoute); parseBool(details, Conf::CONFIG_ACCOUNT_IP_AUTO_REWRITE, allowIPAutoRewrite); parseString(details, Conf::CONFIG_LOCAL_INTERFACE, interface); parseBool(details, Conf::CONFIG_PUBLISHED_SAMEAS_LOCAL, publishedSameasLocal); parseString(details, Conf::CONFIG_PUBLISHED_ADDRESS, publishedIp); parseInt(details, Conf::CONFIG_PUBLISHED_PORT, publishedPort); parseBool(details, Conf::CONFIG_PRESENCE_ENABLED, presenceEnabled); parseString(details, Conf::CONFIG_ACCOUNT_DTMF_TYPE, dtmfType); parseBool(details, Conf::CONFIG_KEEP_ALIVE_ENABLED, registrationRefreshEnabled); parseInt(details, Conf::CONFIG_ACCOUNT_REGISTRATION_EXPIRE, registrationExpire); // srtp settings parseBool(details, Conf::CONFIG_SRTP_RTP_FALLBACK, srtpFallback); auto iter = details.find(Conf::CONFIG_SRTP_KEY_EXCHANGE); if (iter != details.end()) srtpKeyExchange = sip_utils::getKeyExchangeProtocol(iter->second); if (credentials.empty()) { // credentials not set, construct 1 entry JAMI_WARN("No credentials set, inferring them..."); std::map<std::string, std::string> map; map[Conf::CONFIG_ACCOUNT_USERNAME] = username; parseString(details, Conf::CONFIG_ACCOUNT_PASSWORD, map[Conf::CONFIG_ACCOUNT_PASSWORD]); map[Conf::CONFIG_ACCOUNT_REALM] = "*"; setCredentials({map}); } // ICE - STUN parseBool(details, Conf::CONFIG_STUN_ENABLE, stunEnabled); parseString(details, Conf::CONFIG_STUN_SERVER, stunServer); // TLS parseBool(details, Conf::CONFIG_TLS_ENABLE, tlsEnable); parseInt(details, Conf::CONFIG_TLS_LISTENER_PORT, tlsListenerPort); parsePath(details, Conf::CONFIG_TLS_CA_LIST_FILE, tlsCaListFile, path); parsePath(details, Conf::CONFIG_TLS_CERTIFICATE_FILE, tlsCertificateFile, path); parsePath(details, Conf::CONFIG_TLS_PRIVATE_KEY_FILE, tlsPrivateKeyFile, path); parseString(details, Conf::CONFIG_TLS_PASSWORD, tlsPassword); parseString(details, Conf::CONFIG_TLS_METHOD, tlsMethod); parseString(details, Conf::CONFIG_TLS_CIPHERS, tlsCiphers); parseString(details, Conf::CONFIG_TLS_SERVER_NAME, tlsServerName); parseBool(details, Conf::CONFIG_TLS_VERIFY_SERVER, tlsVerifyServer); parseBool(details, Conf::CONFIG_TLS_VERIFY_CLIENT, tlsVerifyClient); parseBool(details, Conf::CONFIG_TLS_REQUIRE_CLIENT_CERTIFICATE, tlsRequireClientCertificate); parseBool(details, Conf::CONFIG_TLS_DISABLE_SECURE_DLG_CHECK, tlsDisableSecureDlgCheck); parseInt(details, Conf::CONFIG_TLS_NEGOTIATION_TIMEOUT_SEC, tlsNegotiationTimeout); } SipAccountConfig::Credentials::Credentials(const std::map<std::string, std::string>& cred) { auto itrealm = cred.find(Conf::CONFIG_ACCOUNT_REALM); auto user = cred.find(Conf::CONFIG_ACCOUNT_USERNAME); auto passw = cred.find(Conf::CONFIG_ACCOUNT_PASSWORD); realm = itrealm != cred.end() ? itrealm->second : ""; username = user != cred.end() ? user->second : ""; password = passw != cred.end() ? passw->second : ""; computePasswordHash(); } std::map<std::string, std::string> SipAccountConfig::Credentials::toMap() const { return {{Conf::CONFIG_ACCOUNT_REALM, realm}, {Conf::CONFIG_ACCOUNT_USERNAME, username}, {Conf::CONFIG_ACCOUNT_PASSWORD, password}}; } void SipAccountConfig::Credentials::computePasswordHash() { pj_md5_context pms; /* Compute md5 hash = MD5(username ":" realm ":" password) */ pj_md5_init(&pms); pj_md5_update(&pms, (const uint8_t*) username.data(), username.length()); pj_md5_update(&pms, (const uint8_t*) ":", 1); pj_md5_update(&pms, (const uint8_t*) realm.data(), realm.length()); pj_md5_update(&pms, (const uint8_t*) ":", 1); pj_md5_update(&pms, (const uint8_t*) password.data(), password.length()); unsigned char digest[16]; pj_md5_final(&pms, digest); char hash[32]; for (int i = 0; i < 16; ++i) pj_val_to_hex_digit(digest[i], &hash[2 * i]); password_h = {hash, 32}; } std::vector<std::map<std::string, std::string>> SipAccountConfig::getCredentials() const { std::vector<std::map<std::string, std::string>> ret; ret.reserve(credentials.size()); for (const auto& c : credentials) { ret.emplace_back(c.toMap()); } return ret; } void SipAccountConfig::setCredentials(const std::vector<std::map<std::string, std::string>>& creds) { credentials.clear(); credentials.reserve(creds.size()); for (const auto& cred : creds) credentials.emplace_back(cred); } }
16,918
C++
.cpp
315
49.015873
111
0.715623
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,841
pres_sub_server.cpp
savoirfairelinux_jami-daemon/src/sip/pres_sub_server.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "pjsip/sip_multipart.h" #include "sip/sipaccount.h" #include "sip/sipvoiplink.h" #include "manager.h" #include "sip/sippresence.h" #include "logger.h" #include "pres_sub_server.h" #include "client/ring_signal.h" #include "connectivity/sip_utils.h" #include "compiler_intrinsics.h" namespace jami { using sip_utils::CONST_PJ_STR; /* Callback called when *server* subscription state has changed. */ void PresSubServer::pres_evsub_on_srv_state(UNUSED pjsip_evsub* sub, UNUSED pjsip_event* event) { JAMI_ERR("PresSubServer::pres_evsub_on_srv_state() is deprecated and does nothing"); return; #if 0 // DISABLED: removed IP2IP support, tuleap: #448 pjsip_rx_data *rdata = event->body.rx_msg.rdata; if (!rdata) { JAMI_DBG("Presence_subscription_server estate has changed but no rdata."); return; } auto account = Manager::instance().getIP2IPAccount(); auto sipaccount = static_cast<SIPAccount *>(account.get()); if (!sipaccount) { JAMI_ERR("Unable to find account IP2IP"); return; } auto pres = sipaccount->getPresence(); if (!pres) { JAMI_ERR("Presence not initialized"); return; } pres->lock(); PresSubServer *presSubServer = static_cast<PresSubServer *>(pjsip_evsub_get_mod_data(sub, pres->getModId())); if (presSubServer) { JAMI_DBG("Presence_subscription_server to %s is %s", presSubServer->remote_, pjsip_evsub_get_state_name(sub)); pjsip_evsub_state state; state = pjsip_evsub_get_state(sub); if (state == PJSIP_EVSUB_STATE_TERMINATED) { pjsip_evsub_set_mod_data(sub, pres->getModId(), NULL); pres->removePresSubServer(presSubServer); } /* TODO check if other cases should be handled*/ } pres->unlock(); #endif } pj_bool_t PresSubServer::pres_on_rx_subscribe_request(pjsip_rx_data* rdata) { pjsip_method* method = &rdata->msg_info.msg->line.req.method; pj_str_t* str = &method->name; std::string request(str->ptr, str->slen); // pj_str_t contact; #if 0 // DISABLED: removed IP2IP support, tuleap: #448 pj_status_t status; pjsip_dialog *dlg; pjsip_evsub *sub; pjsip_evsub_user pres_cb; pjsip_expires_hdr *expires_hdr; pjsip_status_code st_code; pj_str_t reason; pres_msg_data msg_data; pjsip_evsub_state ev_state; #endif /* Only hande incoming subscribe messages should be processed here. * Otherwise we return FALSE to let other modules handle it */ if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_subscribe_method()) != 0) return PJ_FALSE; JAMI_ERR("PresSubServer::pres_evsub_on_srv_state() is deprecated and does nothing"); return PJ_FALSE; #if 0 // DISABLED: removed IP2IP support, tuleap: #448 /* debug msg */ std::string name(rdata->msg_info.to->name.ptr, rdata->msg_info.to->name.slen); std::string server(rdata->msg_info.from->name.ptr, rdata->msg_info.from->name.slen); JAMI_DBG("Incoming pres_on_rx_subscribe_request for %s, name:%s, server:%s." , request.c_str() , name.c_str() , server.c_str()); /* get parents*/ auto account = Manager::instance().getIP2IPAccount(); auto sipaccount = static_cast<SIPAccount *>(account.get()); if (!sipaccount) { JAMI_ERR("Unable to find account IP2IP"); return PJ_FALSE; } pjsip_endpoint *endpt = Manager::instance().sipVoIPLink().getEndpoint(); SIPPresence * pres = sipaccount->getPresence(); pres->lock(); /* Create UAS dialog: */ const pj_str_t contact(sipaccount->getContactHeader()); status = pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, &contact, &dlg); if (status != PJ_SUCCESS) { char errmsg[PJ_ERR_MSG_SIZE]; pj_strerror(status, errmsg, sizeof(errmsg)); JAMI_WARN("Unable to create UAS dialog for subscription: %s [status=%d]", errmsg, status); pres->unlock(); pjsip_endpt_respond_stateless(endpt, rdata, 400, NULL, NULL, NULL); return PJ_TRUE; } /* Init callback: */ pj_bzero(&pres_cb, sizeof(pres_cb)); pres_cb.on_evsub_state = &pres_evsub_on_srv_state; /* Create server presence subscription: */ status = pjsip_pres_create_uas(dlg, &pres_cb, rdata, &sub); if (status != PJ_SUCCESS) { int code = PJSIP_ERRNO_TO_SIP_STATUS(status); pjsip_tx_data *tdata; JAMI_WARN("Unable to create server subscription %d", status); if (code == 599 || code > 699 || code < 300) { code = 400; } status = pjsip_dlg_create_response(dlg, rdata, code, NULL, &tdata); if (status == PJ_SUCCESS) { pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata); } pres->unlock(); return PJ_FALSE; } /* Attach our data to the subscription: */ char* remote = (char*) pj_pool_alloc(dlg->pool, PJSIP_MAX_URL_SIZE); status = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, dlg->remote.info->uri, remote, PJSIP_MAX_URL_SIZE); if (status < 1) pj_ansi_strcpy(remote, "<-- url is too long-->"); else remote[status] = '\0'; //pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, dlg->local.info->uri, contact.ptr, PJSIP_MAX_URL_SIZE); /* Create a new PresSubServer server and wait for client approve */ PresSubServer *presSubServer = new PresSubServer(pres, sub, remote, dlg); pjsip_evsub_set_mod_data(sub, pres->getModId(), presSubServer); // Notify the client. emitSignal<libjami::PresenceSignal::NewServerSubscriptionRequest>(presSubServer->remote_); pres->addPresSubServer(presSubServer); /* Capture the value of Expires header. */ expires_hdr = (pjsip_expires_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL); if (expires_hdr) presSubServer->setExpires(expires_hdr->ivalue); else presSubServer->setExpires(-1); st_code = (pjsip_status_code) 200; reason = CONST_PJ_STR("OK"); pj_bzero(&msg_data, sizeof(msg_data)); pj_list_init(&msg_data.hdr_list); pjsip_media_type_init(&msg_data.multipart_ctype, NULL, NULL); pj_list_init(&msg_data.multipart_parts); /* Create and send 2xx response to the SUBSCRIBE request: */ status = pjsip_pres_accept(sub, rdata, st_code, &msg_data.hdr_list); if (status != PJ_SUCCESS) { JAMI_WARN("Unable to accept presence subscription %d", status); pjsip_pres_terminate(sub, PJ_FALSE); pres->unlock(); return PJ_FALSE; } // Unsubscribe case ev_state = PJSIP_EVSUB_STATE_ACTIVE; if (presSubServer->getExpires() == 0) { // PJSIP_EVSUB_STATE_TERMINATED pres->unlock(); return PJ_TRUE; } /*Send notify immediately. Replace real status with fake.*/ // pjsip_pres_set_status(sub, pres->getStatus()); // real status // fake temporary status pjrpid_element rpid = { PJRPID_ELEMENT_TYPE_PERSON, CONST_PJ_STR("20"), PJRPID_ACTIVITY_UNKNOWN, CONST_PJ_STR("") // empty note by default }; pjsip_pres_status fake_status_data; pj_bzero(&fake_status_data, sizeof(pjsip_pres_status)); fake_status_data.info_cnt = 1; fake_status_data.info[0].basic_open = false; fake_status_data.info[0].id = CONST_PJ_STR("0"); /* todo: tuplie_id*/ pj_memcpy(&fake_status_data.info[0].rpid, &rpid, sizeof(pjrpid_element)); pjsip_pres_set_status(sub, &fake_status_data); /* Create and send the the first NOTIFY to active subscription: */ pj_str_t stateStr = CONST_PJ_STR(""); pjsip_tx_data *tdata = NULL; status = pjsip_pres_notify(sub, ev_state, &stateStr, &reason, &tdata); if (status == PJ_SUCCESS) { pres->fillDoc(tdata, &msg_data); status = pjsip_pres_send_request(sub, tdata); } if (status != PJ_SUCCESS) { JAMI_WARN("Unable to create/send NOTIFY %d", status); pjsip_pres_terminate(sub, PJ_FALSE); pres->unlock(); return status; } pres->unlock(); return PJ_TRUE; #endif } pjsip_module PresSubServer::mod_presence_server = { NULL, NULL, /* prev, next. */ CONST_PJ_STR("mod-presence-server"), /* Name. */ -1, /* Id */ PJSIP_MOD_PRIORITY_DIALOG_USAGE, NULL, /* load() */ NULL, /* start() */ NULL, /* stop() */ NULL, /* unload() */ &pres_on_rx_subscribe_request, /* on_rx_request() */ NULL, /* on_rx_response() */ NULL, /* on_tx_request. */ NULL, /* on_tx_response() */ NULL, /* on_tsx_state() */ }; PresSubServer::PresSubServer(SIPPresence* pres, pjsip_evsub* evsub, const char* remote, pjsip_dialog* d) : remote_(remote) , pres_(pres) , sub_(evsub) , dlg_(d) , expires_(-1) , approved_(false) {} PresSubServer::~PresSubServer() { // TODO: check if evsub needs to be forced TERMINATED. } void PresSubServer::setExpires(int ms) { expires_ = ms; } int PresSubServer::getExpires() const { return expires_; } bool PresSubServer::matches(const char* s) const { // servers match if they have the same remote uri and the account ID. return (!(strcmp(remote_, s))); } void PresSubServer::approve(bool flag) { approved_ = flag; JAMI_DBG("Approve Presence_subscription_server for %s: %s.", remote_, flag ? "true" : "false"); // attach the real status data pjsip_pres_set_status(sub_, pres_->getStatus()); } void PresSubServer::notify() { /* Only send NOTIFY once subscription is active. Some subscriptions * may still be in NULL (when app is adding a new buddy while in the * on_incoming_subscribe() callback) or PENDING (when user approval is * being requested) state and we don't send NOTIFY to these subs until * the user accepted the request. */ if ((pjsip_evsub_get_state(sub_) == PJSIP_EVSUB_STATE_ACTIVE) && (approved_)) { JAMI_DBG("Notifying %s.", remote_); pjsip_tx_data* tdata; pjsip_pres_set_status(sub_, pres_->getStatus()); if (pjsip_pres_current_notify(sub_, &tdata) == PJ_SUCCESS) { // add msg header and send pres_->fillDoc(tdata, NULL); pjsip_pres_send_request(sub_, tdata); } else { JAMI_WARN("Unable to create/send NOTIFY"); pjsip_pres_terminate(sub_, PJ_FALSE); } } } } // namespace jami
11,560
C++
.cpp
293
33.764505
113
0.629005
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,842
callmanager.cpp
savoirfairelinux_jami-daemon/src/client/callmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <vector> #include <cstring> #include "callmanager_interface.h" #include "call_factory.h" #include "client/ring_signal.h" #include "sip/siptransport.h" #include "sip/sipvoiplink.h" #include "sip/sipcall.h" #include "audio/audiolayer.h" #include "media/media_attribute.h" #include "string_utils.h" #include "logger.h" #include "manager.h" #include "jamidht/jamiaccount.h" namespace libjami { void registerCallHandlers(const std::map<std::string, std::shared_ptr<CallbackWrapperBase>>& handlers) { registerSignalHandlers(handlers); } std::string placeCall(const std::string& accountId, const std::string& to) { // TODO. Remove ASAP. JAMI_WARN("This API is deprecated, use placeCallWithMedia() instead"); return placeCallWithMedia(accountId, to, {}); } std::string placeCallWithMedia(const std::string& accountId, const std::string& to, const std::vector<libjami::MediaMap>& mediaList) { // Check if a destination number is available if (to.empty()) { JAMI_DBG("No number entered - Call aborted"); return {}; } else { return jami::Manager::instance().outgoingCall(accountId, to, mediaList); } } bool requestMediaChange(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap>& mediaList) { if (auto account = jami::Manager::instance().getAccount(accountId)) { if (auto call = account->getCall(callId)) { return call->requestMediaChange(mediaList); } else if (auto conf = account->getConference(callId)) { return conf->requestMediaChange(mediaList); } } return false; } bool refuse(const std::string& accountId, const std::string& callId) { return jami::Manager::instance().refuseCall(accountId, callId); } bool accept(const std::string& accountId, const std::string& callId) { return jami::Manager::instance().answerCall(accountId, callId); } bool acceptWithMedia(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap>& mediaList) { return jami::Manager::instance().answerCall(accountId, callId, mediaList); } bool answerMediaChangeRequest(const std::string& accountId, const std::string& callId, const std::vector<libjami::MediaMap>& mediaList) { if (auto account = jami::Manager::instance().getAccount(accountId)) if (auto call = account->getCall(callId)) { try { call->answerMediaChangeRequest(mediaList); return true; } catch (const std::runtime_error& e) { JAMI_ERR("%s", e.what()); } } return false; } bool hangUp(const std::string& accountId, const std::string& callId) { return jami::Manager::instance().hangupCall(accountId, callId); } bool hangUpConference(const std::string& accountId, const std::string& confId) { return jami::Manager::instance().hangupConference(accountId, confId); } bool hold(const std::string& accountId, const std::string& callId) { return jami::Manager::instance().onHoldCall(accountId, callId); } bool unhold(const std::string& accountId, const std::string& callId) { return jami::Manager::instance().offHoldCall(accountId, callId); } bool muteLocalMedia(const std::string& accountId, const std::string& callId, const std::string& mediaType, bool mute) { if (auto account = jami::Manager::instance().getAccount(accountId)) { if (auto call = account->getCall(callId)) { JAMI_DBG("Muting [%s] for call %s", mediaType.c_str(), callId.c_str()); call->muteMedia(mediaType, mute); return true; } else if (auto conf = account->getConference(callId)) { JAMI_DBG("Muting local host [%s] for conference %s", mediaType.c_str(), callId.c_str()); conf->muteLocalHost(mute, mediaType); return true; } else { JAMI_WARN("ID %s doesn't match any call or conference", callId.c_str()); } } return false; } bool transfer(const std::string& accountId, const std::string& callId, const std::string& to) { return jami::Manager::instance().transferCall(accountId, callId, to); } bool attendedTransfer(const std::string& accountId, const std::string& transferID, const std::string& targetID) { if (auto account = jami::Manager::instance().getAccount(accountId)) if (auto call = account->getCall(transferID)) return call->attendedTransfer(targetID); return false; } bool joinParticipant(const std::string& accountId, const std::string& sel_callId, const std::string& account2Id, const std::string& drag_callId) { return jami::Manager::instance().joinParticipant(accountId, sel_callId, account2Id, drag_callId); } void createConfFromParticipantList(const std::string& accountId, const std::vector<std::string>& participants) { jami::Manager::instance().createConfFromParticipantList(accountId, participants); } void setConferenceLayout(const std::string& accountId, const std::string& confId, uint32_t layout) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->setLayout(layout); } else if (auto call = account->getCall(confId)) { Json::Value root; root["layout"] = layout; call->sendConfOrder(root); } } } bool isConferenceParticipant(const std::string& accountId, const std::string& callId) { if (auto account = jami::Manager::instance().getAccount(accountId)) if (auto call = account->getCall(callId)) return call->isConferenceParticipant(); return false; } void startSmartInfo(uint32_t refreshTimeMs) { JAMI_WARNING("startSmartInfo is deprecated and does nothing."); } void stopSmartInfo() { JAMI_WARNING("stopSmartInfo is deprecated and does nothing."); } bool addParticipant(const std::string& accountId, const std::string& callId, const std::string& account2Id, const std::string& confId) { return jami::Manager::instance().addSubCall(accountId, callId, account2Id, confId); } bool addMainParticipant(const std::string& accountId, const std::string& confId) { return jami::Manager::instance().addMainParticipant(accountId, confId); } bool detachLocalParticipant() { return jami::Manager::instance().detachHost(); } bool detachParticipant(const std::string&, const std::string& callId) { return jami::Manager::instance().detachParticipant(callId); } bool joinConference(const std::string& accountId, const std::string& sel_confId, const std::string& account2Id, const std::string& drag_confId) { return jami::Manager::instance().joinConference(accountId, sel_confId, account2Id, drag_confId); } bool holdConference(const std::string& accountId, const std::string& confId) { return jami::Manager::instance().holdConference(accountId, confId); } bool unholdConference(const std::string& accountId, const std::string& confId) { return jami::Manager::instance().unHoldConference(accountId, confId); } std::map<std::string, std::string> getConferenceDetails(const std::string& accountId, const std::string& confId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) if (auto conf = account->getConference(confId)) return {{"ID", confId}, {"STATE", conf->getStateStr()}, #ifdef ENABLE_VIDEO {"VIDEO_SOURCE", conf->getVideoInput()}, #endif {"RECORDING", conf->isRecording() ? jami::TRUE_STR : jami::FALSE_STR}}; return {}; } std::vector<std::map<std::string, std::string>> currentMediaList(const std::string& accountId, const std::string& callId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto call = account->getCall(callId)) { return call->currentMediaList(); } else if (auto conf = account->getConference(callId)) { return conf->currentMediaList(); } } JAMI_WARN("Call not found %s", callId.c_str()); return {}; } std::vector<std::string> getConferenceList(const std::string& accountId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) return account->getConferenceList(); return {}; } std::vector<std::string> getParticipantList(const std::string& accountId, const std::string& confId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) if (auto conf = account->getConference(confId)) { const auto& subcalls(conf->getSubCalls()); return {subcalls.begin(), subcalls.end()}; } return {}; } std::string getConferenceId(const std::string& accountId, const std::string& callId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) if (auto call = account->getCall(callId)) if (auto conf = call->getConference()) return conf->getConfId(); return {}; } bool startRecordedFilePlayback(const std::string& filepath) { return jami::Manager::instance().startRecordedFilePlayback(filepath); } void stopRecordedFilePlayback() { jami::Manager::instance().stopRecordedFilePlayback(); } bool toggleRecording(const std::string& accountId, const std::string& callId) { return jami::Manager::instance().toggleRecordingCall(accountId, callId); } void setRecording(const std::string& accountId, const std::string& callId) { toggleRecording(accountId, callId); } void recordPlaybackSeek(double value) { jami::Manager::instance().recordingPlaybackSeek(value); } bool getIsRecording(const std::string& accountId, const std::string& callId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto call = account->getCall(callId)) { return call->isRecording(); } else if (auto conf = account->getConference(callId)) { return conf->isRecording(); } } return false; } std::map<std::string, std::string> getCallDetails(const std::string& accountId, const std::string& callId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) if (auto call = account->getCall(callId)) return call->getDetails(); return {}; } std::vector<std::string> getCallList() { return jami::Manager::instance().getCallList(); } std::vector<std::string> getCallList(const std::string& accountId) { if (accountId.empty()) return jami::Manager::instance().getCallList(); else if (const auto account = jami::Manager::instance().getAccount(accountId)) return account->getCallList(); JAMI_WARN("Unknown account: %s", accountId.c_str()); return {}; } std::vector<std::map<std::string, std::string>> getConferenceInfos(const std::string& accountId, const std::string& confId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) return conf->getConferenceInfos(); else if (auto call = account->getCall(confId)) return call->getConferenceInfos(); } return {}; } void playDTMF(const std::string& key) { auto code = key.data()[0]; jami::Manager::instance().playDtmf(code); if (auto current_call = jami::Manager::instance().getCurrentCall()) current_call->carryingDTMFdigits(code); } void startTone(int32_t start, int32_t type) { if (start) { if (type == 0) jami::Manager::instance().playTone(); else jami::Manager::instance().playToneWithMessage(); } else jami::Manager::instance().stopTone(); } bool switchInput(const std::string& accountId, const std::string& callId, const std::string& resource) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(callId)) { conf->switchInput(resource); return true; } else if (auto call = account->getCall(callId)) { call->switchInput(resource); return true; } } return false; } bool switchSecondaryInput(const std::string& accountId, const std::string& confId, const std::string& resource) { JAMI_ERR("Use requestMediaChange"); return false; } void sendTextMessage(const std::string& accountId, const std::string& callId, const std::map<std::string, std::string>& messages, const std::string& from, bool isMixed) { jami::runOnMainThread([accountId, callId, messages, from, isMixed] { jami::Manager::instance().sendCallTextMessage(accountId, callId, messages, from, isMixed); }); } void setModerator(const std::string& accountId, const std::string& confId, const std::string& peerId, const bool& state) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->setModerator(peerId, state); } else { JAMI_WARN("Fail to change moderator %s, conference %s not found", peerId.c_str(), confId.c_str()); } } } void muteParticipant(const std::string& accountId, const std::string& confId, const std::string& peerId, const bool& state) { JAMI_ERR() << "muteParticipant is deprecated, please use muteStream"; if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->muteParticipant(peerId, state); } else if (auto call = account->getCall(confId)) { Json::Value root; root["muteParticipant"] = peerId; root["muteState"] = state ? jami::TRUE_STR : jami::FALSE_STR; call->sendConfOrder(root); } } } void muteStream(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId, const std::string& streamId, const bool& state) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->muteStream(accountUri, deviceId, streamId, state); } else if (auto call = account->getCall(confId)) { if (call->conferenceProtocolVersion() == 1) { Json::Value sinkVal; sinkVal["muteAudio"] = state; Json::Value mediasObj; mediasObj[streamId] = sinkVal; Json::Value deviceVal; deviceVal["medias"] = mediasObj; Json::Value deviceObj; deviceObj[deviceId] = deviceVal; Json::Value accountVal; deviceVal["devices"] = deviceObj; Json::Value root; root[accountUri] = deviceVal; root["version"] = 1; call->sendConfOrder(root); } else if (call->conferenceProtocolVersion() == 0) { Json::Value root; root["muteParticipant"] = accountUri; root["muteState"] = state ? jami::TRUE_STR : jami::FALSE_STR; call->sendConfOrder(root); } } } } void setActiveParticipant(const std::string& accountId, const std::string& confId, const std::string& participant) { JAMI_ERR() << "setActiveParticipant is deprecated, please use setActiveStream"; if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->setActiveParticipant(participant); } else if (auto call = account->getCall(confId)) { Json::Value root; root["activeParticipant"] = participant; call->sendConfOrder(root); } } } void setActiveStream(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId, const std::string& streamId, const bool& state) { if (const auto account = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { if (auto conf = account->getConference(confId)) { conf->setActiveStream(streamId, state); } else if (auto call = std::static_pointer_cast<jami::SIPCall>(account->getCall(confId))) { call->setActiveMediaStream(accountUri, deviceId, streamId, state); } } } void hangupParticipant(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId) { if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { conf->hangupParticipant(accountUri, deviceId); } else if (auto call = std::static_pointer_cast<jami::SIPCall>(account->getCall(confId))) { if (call->conferenceProtocolVersion() == 1) { Json::Value deviceVal; deviceVal["hangup"] = jami::TRUE_STR; Json::Value deviceObj; deviceObj[deviceId] = deviceVal; Json::Value accountVal; deviceVal["devices"] = deviceObj; Json::Value root; root[accountUri] = deviceVal; root["version"] = 1; call->sendConfOrder(root); } else if (call->conferenceProtocolVersion() == 0) { Json::Value root; root["hangupParticipant"] = accountUri; call->sendConfOrder(root); } } } } void raiseParticipantHand(const std::string& accountId, const std::string& confId, const std::string& peerId, const bool& state) { JAMI_ERR() << "raiseParticipantHand is deprecated, please use raiseHand"; if (const auto account = jami::Manager::instance().getAccount(accountId)) { if (auto conf = account->getConference(confId)) { if (auto call = std::static_pointer_cast<jami::SIPCall>( conf->getCallFromPeerID(peerId))) { if (auto* transport = call->getTransport()) conf->setHandRaised(std::string(transport->deviceId()), state); } } else if (auto call = account->getCall(confId)) { Json::Value root; root["handRaised"] = peerId; root["handState"] = state ? jami::TRUE_STR : jami::FALSE_STR; call->sendConfOrder(root); } } } void raiseHand(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId, const bool& state) { if (const auto account = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { if (auto conf = account->getConference(confId)) { auto device = deviceId; if (device.empty()) device = std::string(account->currentDeviceId()); conf->setHandRaised(device, state); } else if (auto call = std::static_pointer_cast<jami::SIPCall>(account->getCall(confId))) { if (call->conferenceProtocolVersion() == 1) { Json::Value deviceVal; deviceVal["raiseHand"] = state; Json::Value deviceObj; std::string device = deviceId.empty() ? std::string(account->currentDeviceId()) : deviceId; deviceObj[device] = deviceVal; Json::Value accountVal; deviceVal["devices"] = deviceObj; Json::Value root; std::string uri = accountUri.empty() ? account->getUsername() : accountUri; root[uri] = deviceVal; root["version"] = 1; call->sendConfOrder(root); } else if (call->conferenceProtocolVersion() == 0) { Json::Value root; root["handRaised"] = account->getUsername(); root["handState"] = state ? jami::TRUE_STR : jami::FALSE_STR; call->sendConfOrder(root); } } } } } // namespace libjami
21,826
C++
.cpp
611
28.504092
101
0.631211
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,843
presencemanager.cpp
savoirfairelinux_jami-daemon/src/client/presencemanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "presencemanager_interface.h" #include <cerrno> #include <sstream> #include <cstring> #include "logger.h" #include "manager.h" #include "sip/sipaccount.h" #include "sip/sippresence.h" #include "sip/pres_sub_client.h" #include "client/ring_signal.h" #include "compiler_intrinsics.h" #include "jamidht/jamiaccount.h" namespace libjami { using jami::SIPAccount; void registerPresHandlers(const std::map<std::string, std::shared_ptr<CallbackWrapperBase>>& handlers) { registerSignalHandlers(handlers); } /** * Un/subscribe to buddySipUri for an accountId */ void subscribeBuddy(const std::string& accountId, const std::string& uri, bool flag) { if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) { auto pres = sipaccount->getPresence(); if (pres and pres->isEnabled() and pres->isSupported(PRESENCE_FUNCTION_SUBSCRIBE)) { JAMI_DEBUG("{}ubscribePresence (acc:{}, buddy:{})", flag ? "S" : "Uns", accountId, uri); pres->subscribeClient(uri, flag); } } else if (auto ringaccount = jami::Manager::instance().getAccount<jami::JamiAccount>( accountId)) { ringaccount->trackBuddyPresence(uri, flag); } else JAMI_ERROR("Unable to find account {}", accountId); } /** * push a presence for a account * Notify for IP2IP account * For JamiAccount status is ignored but note is used */ void publish(const std::string& accountId, bool status, const std::string& note) { if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) { auto pres = sipaccount->getPresence(); if (pres and pres->isEnabled() and pres->isSupported(PRESENCE_FUNCTION_PUBLISH)) { JAMI_DEBUG("Send Presence (acc:{}, status {}).", accountId, status ? "online" : "offline"); pres->sendPresence(status, note); } } else if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>( accountId)) { acc->sendPresenceNote(note); } else JAMI_ERROR("Unable to find account {}", accountId); } /** * Accept or not a PresSubServer request for IP2IP account */ void answerServerRequest(UNUSED const std::string& uri, UNUSED bool flag) { #if 0 // DISABLED: removed IP2IP support, tuleap: #448 auto account = jami::Manager::instance().getIP2IPAccount(); if (auto sipaccount = static_cast<SIPAccount *>(account.get())) { JAMI_DEBUG("Approve presence (acc:IP2IP, serv:{}, flag:{})", uri, flag); if (auto pres = sipaccount->getPresence()) pres->approvePresSubServer(uri, flag); else JAMI_ERROR("Presence not initialized"); } else JAMI_ERROR("Unable to find account IP2IP"); #else JAMI_ERROR("answerServerRequest() is deprecated and does nothing"); #endif } /** * Get all active subscriptions for "accountId" */ std::vector<std::map<std::string, std::string>> getSubscriptions(const std::string& accountId) { std::vector<std::map<std::string, std::string>> ret; if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) { if (auto pres = sipaccount->getPresence()) { const auto& subs = pres->getClientSubscriptions(); ret.reserve(subs.size()); for (const auto& s : subs) { ret.push_back( {{libjami::Presence::BUDDY_KEY, std::string(s->getURI())}, {libjami::Presence::STATUS_KEY, s->isPresent() ? libjami::Presence::ONLINE_KEY : libjami::Presence::OFFLINE_KEY}, {libjami::Presence::LINESTATUS_KEY, std::string(s->getLineStatus())}}); } } else JAMI_ERROR("Presence not initialized"); } else if (auto ringaccount = jami::Manager::instance().getAccount<jami::JamiAccount>( accountId)) { const auto& trackedBuddies = ringaccount->getTrackedBuddyPresence(); ret.reserve(trackedBuddies.size()); for (const auto& tracked_id : trackedBuddies) { ret.push_back( {{libjami::Presence::BUDDY_KEY, tracked_id.first}, {libjami::Presence::STATUS_KEY, tracked_id.second ? libjami::Presence::ONLINE_KEY : libjami::Presence::OFFLINE_KEY}}); } } else JAMI_ERROR("Unable to find account {}", accountId); return ret; } /** * Batch subscribing of URIs */ void setSubscriptions(const std::string& accountId, const std::vector<std::string>& uris) { if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) { if (auto pres = sipaccount->getPresence()) { for (const auto& u : uris) pres->subscribeClient(u, true); } else JAMI_ERROR("Presence not initialized"); } else if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>( accountId)) { for (const auto& u : uris) acc->trackBuddyPresence(u, true); } else JAMI_ERROR("Unable to find account {}", accountId); } } // namespace libjami
6,006
C++
.cpp
154
32.636364
134
0.648843
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,844
videomanager.cpp
savoirfairelinux_jami-daemon/src/client/videomanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "videomanager_interface.h" #include "videomanager.h" #include "localrecorder.h" #include "localrecordermanager.h" #include "libav_utils.h" #include "video/video_input.h" #include "video/video_device_monitor.h" #include "account.h" #include "logger.h" #include "manager.h" #include "system_codec_container.h" #ifdef ENABLE_VIDEO #include "video/sinkclient.h" #endif #include "client/ring_signal.h" #include "audio/ringbufferpool.h" #include "jami/media_const.h" #include "libav_utils.h" #include "call_const.h" #include "system_codec_container.h" #include <functional> #include <memory> #include <string> #include <vector> #include <new> // std::bad_alloc #include <algorithm> #include <cstdlib> #include <cstring> // std::memset #include <ciso646> // fix windows compiler bug extern "C" { #include <libavutil/display.h> } namespace libjami { MediaFrame::MediaFrame() : frame_ {av_frame_alloc()} { if (not frame_) throw std::bad_alloc(); } void MediaFrame::copyFrom(const MediaFrame& o) { reset(); if (o.frame_) { av_frame_ref(frame_.get(), o.frame_.get()); av_frame_copy_props(frame_.get(), o.frame_.get()); } if (o.packet_) { packet_.reset(av_packet_alloc()); av_packet_ref(packet_.get(), o.packet_.get()); } } void MediaFrame::reset() noexcept { if (frame_) av_frame_unref(frame_.get()); packet_.reset(); } void MediaFrame::setPacket(PacketBuffer&& pkt) { packet_ = std::move(pkt); } AudioFrame::AudioFrame(const jami::AudioFormat& format, size_t nb_samples) : MediaFrame() { setFormat(format); if (nb_samples) reserve(nb_samples); } void AudioFrame::setFormat(const jami::AudioFormat& format) { auto d = pointer(); av_channel_layout_default(&d->ch_layout, format.nb_channels); d->sample_rate = format.sample_rate; d->format = format.sampleFormat; } jami::AudioFormat AudioFrame::getFormat() const { return {(unsigned) frame_->sample_rate, (unsigned) frame_->ch_layout.nb_channels, (AVSampleFormat) frame_->format}; } size_t AudioFrame::getFrameSize() const { return frame_->nb_samples; } void AudioFrame::reserve(size_t nb_samples) { if (nb_samples != 0) { auto d = pointer(); d->nb_samples = nb_samples; int err; if ((err = av_frame_get_buffer(d, 0)) < 0) { throw std::bad_alloc(); } } } void AudioFrame::mix(const AudioFrame& frame) { auto& f = *pointer(); auto& fIn = *frame.pointer(); if (f.ch_layout.nb_channels != fIn.ch_layout.nb_channels || f.format != fIn.format || f.sample_rate != fIn.sample_rate) { throw std::invalid_argument("Unable to mix frames with different formats"); } if (f.nb_samples == 0) { reserve(fIn.nb_samples); jami::libav_utils::fillWithSilence(&f); } else if (f.nb_samples != fIn.nb_samples) { throw std::invalid_argument("Unable to mix frames with different length"); } AVSampleFormat fmt = (AVSampleFormat) f.format; bool isPlanar = av_sample_fmt_is_planar(fmt); unsigned samplesPerChannel = isPlanar ? f.nb_samples : f.nb_samples * f.ch_layout.nb_channels; unsigned channels = isPlanar ? f.ch_layout.nb_channels : 1; if (fmt == AV_SAMPLE_FMT_S16 || fmt == AV_SAMPLE_FMT_S16P) { for (unsigned i = 0; i < channels; i++) { auto c = (int16_t*) f.extended_data[i]; auto cIn = (int16_t*) fIn.extended_data[i]; for (unsigned s = 0; s < samplesPerChannel; s++) { c[s] = std::clamp((int32_t) c[s] + (int32_t) cIn[s], (int32_t) std::numeric_limits<int16_t>::min(), (int32_t) std::numeric_limits<int16_t>::max()); } } } else if (fmt == AV_SAMPLE_FMT_FLT || fmt == AV_SAMPLE_FMT_FLTP) { for (unsigned i = 0; i < channels; i++) { auto c = (float*) f.extended_data[i]; auto cIn = (float*) fIn.extended_data[i]; for (unsigned s = 0; s < samplesPerChannel; s++) { c[s] += cIn[s]; } } } else { throw std::invalid_argument(std::string("Unsupported format for mixing: ") + av_get_sample_fmt_name(fmt)); } } float AudioFrame::calcRMS() const { double rms = 0.0; auto fmt = static_cast<AVSampleFormat>(frame_->format); bool planar = av_sample_fmt_is_planar(fmt); int perChannel = planar ? frame_->nb_samples : frame_->nb_samples * frame_->ch_layout.nb_channels; int channels = planar ? frame_->ch_layout.nb_channels : 1; if (fmt == AV_SAMPLE_FMT_S16 || fmt == AV_SAMPLE_FMT_S16P) { for (int c = 0; c < channels; ++c) { auto buf = reinterpret_cast<int16_t*>(frame_->extended_data[c]); for (int i = 0; i < perChannel; ++i) { auto sample = buf[i] * 0.000030517578125f; rms += sample * sample; } } } else if (fmt == AV_SAMPLE_FMT_FLT || fmt == AV_SAMPLE_FMT_FLTP) { for (int c = 0; c < channels; ++c) { auto buf = reinterpret_cast<float*>(frame_->extended_data[c]); for (int i = 0; i < perChannel; ++i) { rms += buf[i] * buf[i]; } } } else { // Should not happen JAMI_ERR() << "Unsupported format for getting volume level: " << av_get_sample_fmt_name(fmt); return 0.0; } // divide by the number of multi-byte samples return sqrt(rms / (frame_->nb_samples * frame_->ch_layout.nb_channels)); } #ifdef ENABLE_VIDEO VideoFrame::~VideoFrame() { if (releaseBufferCb_) releaseBufferCb_(ptr_); } void VideoFrame::reset() noexcept { MediaFrame::reset(); allocated_ = false; releaseBufferCb_ = {}; } void VideoFrame::copyFrom(const VideoFrame& o) { MediaFrame::copyFrom(o); ptr_ = o.ptr_; allocated_ = o.allocated_; } size_t VideoFrame::size() const noexcept { return av_image_get_buffer_size((AVPixelFormat) frame_->format, frame_->width, frame_->height, 1); } int VideoFrame::format() const noexcept { return frame_->format; } int VideoFrame::width() const noexcept { return frame_->width; } int VideoFrame::height() const noexcept { return frame_->height; } void VideoFrame::setGeometry(int format, int width, int height) noexcept { frame_->format = format; frame_->width = width; frame_->height = height; } void VideoFrame::reserve(int format, int width, int height) { auto libav_frame = frame_.get(); if (allocated_) { // nothing to do if same properties if (width == libav_frame->width and height == libav_frame->height and format == libav_frame->format) av_frame_unref(libav_frame); } setGeometry(format, width, height); if (av_frame_get_buffer(libav_frame, 32)) throw std::bad_alloc(); allocated_ = true; releaseBufferCb_ = {}; } void VideoFrame::setFromMemory(uint8_t* ptr, int format, int width, int height) noexcept { reset(); setGeometry(format, width, height); if (not ptr) return; av_image_fill_arrays(frame_->data, frame_->linesize, (uint8_t*) ptr, (AVPixelFormat) frame_->format, width, height, 1); } void VideoFrame::setFromMemory(uint8_t* ptr, int format, int width, int height, const std::function<void(uint8_t*)>& cb) noexcept { setFromMemory(ptr, format, width, height); if (cb) { releaseBufferCb_ = cb; ptr_ = ptr; } } void VideoFrame::setReleaseCb(const std::function<void(uint8_t*)>& cb) noexcept { if (cb) { releaseBufferCb_ = cb; } } void VideoFrame::noise() { auto f = frame_.get(); if (f->data[0] == nullptr) return; for (std::size_t i = 0; i < size(); ++i) { f->data[0][i] = std::rand() & 255; } } int VideoFrame::getOrientation() const { int32_t* matrix {nullptr}; if (auto p = packet()) { matrix = reinterpret_cast<int32_t*>( av_packet_get_side_data(p, AV_PKT_DATA_DISPLAYMATRIX, nullptr)); } else if (auto p = pointer()) { if (AVFrameSideData* side_data = av_frame_get_side_data(p, AV_FRAME_DATA_DISPLAYMATRIX)) { matrix = reinterpret_cast<int32_t*>(side_data->data); } } if (matrix) { double angle = av_display_rotation_get(matrix); return std::isnan(angle) ? 0 : -(int) angle; } return 0; } VideoFrame* getNewFrame(std::string_view id) { if (auto input = jami::Manager::instance().getVideoManager().getVideoInput(id)) return &input->getNewFrame(); JAMI_WARN("getNewFrame: Unable to find input %.*s", (int) id.size(), id.data()); return nullptr; } void publishFrame(std::string_view id) { if (auto input = jami::Manager::instance().getVideoManager().getVideoInput(id)) return input->publishFrame(); JAMI_WARN("publishFrame: Unable to find input %.*s", (int) id.size(), id.data()); } void registerVideoHandlers(const std::map<std::string, std::shared_ptr<CallbackWrapperBase>>& handlers) { registerSignalHandlers(handlers); } std::vector<std::string> getDeviceList() { return jami::Manager::instance().getVideoManager().videoDeviceMonitor.getDeviceList(); } VideoCapabilities getCapabilities(const std::string& deviceId) { return jami::Manager::instance().getVideoManager().videoDeviceMonitor.getCapabilities(deviceId); } std::string getDefaultDevice() { return jami::Manager::instance().getVideoManager().videoDeviceMonitor.getDefaultDevice(); } void setDefaultDevice(const std::string& deviceId) { JAMI_DBG("Setting default device to %s", deviceId.c_str()); if (jami::Manager::instance().getVideoManager().videoDeviceMonitor.setDefaultDevice(deviceId)) jami::Manager::instance().saveConfig(); } void setDeviceOrientation(const std::string& deviceId, int angle) { jami::Manager::instance().getVideoManager().setDeviceOrientation(deviceId, angle); } std::map<std::string, std::string> getDeviceParams(const std::string& deviceId) { auto params = jami::Manager::instance().getVideoManager().videoDeviceMonitor.getDeviceParams( deviceId); std::ostringstream rate; rate << params.framerate; return {{"format", params.format}, {"width", std::to_string(params.width)}, {"height", std::to_string(params.height)}, {"rate", rate.str()}}; } std::map<std::string, std::string> getSettings(const std::string& deviceId) { return jami::Manager::instance() .getVideoManager() .videoDeviceMonitor.getSettings(deviceId) .to_map(); } void applySettings(const std::string& deviceId, const std::map<std::string, std::string>& settings) { jami::Manager::instance().getVideoManager().videoDeviceMonitor.applySettings(deviceId, settings); jami::Manager::instance().saveConfig(); } std::string openVideoInput(const std::string& path) { auto& vm = jami::Manager::instance().getVideoManager(); auto id = path.empty() ? vm.videoDeviceMonitor.getMRLForDefaultDevice() : path; auto& input = vm.clientVideoInputs[id]; if (not input) { input = jami::getVideoInput(id); } return id; } bool closeVideoInput(const std::string& id) { return jami::Manager::instance().getVideoManager().clientVideoInputs.erase(id) > 0; } #endif void startAudioDevice() { auto newPreview = jami::getAudioInput(jami::RingBufferPool::DEFAULT_ID); jami::Manager::instance().getVideoManager().audioPreview = newPreview; newPreview->switchInput(""); } void stopAudioDevice() { jami::Manager::instance().getVideoManager().audioPreview.reset(); } std::string startLocalMediaRecorder(const std::string& videoInputId, const std::string& filepath) { auto rec = std::make_unique<jami::LocalRecorder>(videoInputId); rec->setPath(filepath); // retrieve final path (containing file extension) auto path = rec->getPath(); auto& recordManager = jami::LocalRecorderManager::instance(); try { recordManager.insertRecorder(path, std::move(rec)); } catch (const std::invalid_argument&) { return ""; } auto ret = recordManager.getRecorderByPath(path)->startRecording(); if (!ret) { recordManager.removeRecorderByPath(filepath); return ""; } return path; } void stopLocalRecorder(const std::string& filepath) { jami::LocalRecorder* rec = jami::LocalRecorderManager::instance().getRecorderByPath(filepath); if (!rec) { JAMI_WARN("Unable to stop non existing local recorder."); return; } rec->stopRecording(); jami::LocalRecorderManager::instance().removeRecorderByPath(filepath); } bool registerSinkTarget(const std::string& sinkId, SinkTarget target) { #ifdef ENABLE_VIDEO if (auto sink = jami::Manager::instance().getSinkClient(sinkId)) { sink->registerTarget(std::move(target)); return true; } else JAMI_WARN("No sink found for id '%s'", sinkId.c_str()); #endif return false; } #ifdef ENABLE_SHM void startShmSink(const std::string& sinkId, bool value) { #ifdef ENABLE_VIDEO if (auto sink = jami::Manager::instance().getSinkClient(sinkId)) sink->enableShm(value); else JAMI_WARN("No sink found for id '%s'", sinkId.c_str()); #endif } #endif std::map<std::string, std::string> getRenderer(const std::string& callId) { #ifdef ENABLE_VIDEO if (auto sink = jami::Manager::instance().getSinkClient(callId)) return { {libjami::Media::Details::CALL_ID, callId}, {libjami::Media::Details::SHM_PATH, sink->openedName()}, {libjami::Media::Details::WIDTH, std::to_string(sink->getWidth())}, {libjami::Media::Details::HEIGHT, std::to_string(sink->getHeight())}, }; else #endif return { {libjami::Media::Details::CALL_ID, callId}, {libjami::Media::Details::SHM_PATH, ""}, {libjami::Media::Details::WIDTH, "0"}, {libjami::Media::Details::HEIGHT, "0"}, }; } std::string createMediaPlayer(const std::string& path) { return jami::createMediaPlayer(path); } bool closeMediaPlayer(const std::string& id) { return jami::closeMediaPlayer(id); } bool pausePlayer(const std::string& id, const bool& pause) { return jami::pausePlayer(id, pause); } bool mutePlayerAudio(const std::string& id, const bool& mute) { return jami::mutePlayerAudio(id, mute); } bool playerSeekToTime(const std::string& id, const int& time) { return jami::playerSeekToTime(id, time); } int64_t getPlayerPosition(const std::string& id) { return jami::getPlayerPosition(id); } int64_t getPlayerDuration(const std::string& id) { return jami::getPlayerDuration(id); } void setAutoRestart(const std::string& id, const bool& restart) { jami::setAutoRestart(id, restart); } bool getDecodingAccelerated() { #ifdef RING_ACCEL return jami::Manager::instance().videoPreferences.getDecodingAccelerated(); #else return false; #endif } void setDecodingAccelerated(bool state) { #ifdef RING_ACCEL JAMI_DBG("%s hardware acceleration", (state ? "Enabling" : "Disabling")); if (jami::Manager::instance().videoPreferences.setDecodingAccelerated(state)) jami::Manager::instance().saveConfig(); #endif } bool getEncodingAccelerated() { #ifdef RING_ACCEL return jami::Manager::instance().videoPreferences.getEncodingAccelerated(); #else return false; #endif } void setEncodingAccelerated(bool state) { #ifdef RING_ACCEL JAMI_DBG("%s hardware acceleration", (state ? "Enabling" : "Disabling")); if (jami::Manager::instance().videoPreferences.setEncodingAccelerated(state)) jami::Manager::instance().saveConfig(); else return; #endif for (const auto& acc : jami::Manager::instance().getAllAccounts()) { if (state) acc->setCodecActive(AV_CODEC_ID_HEVC); else acc->setCodecInactive(AV_CODEC_ID_HEVC); // Update and sort codecs acc->setActiveCodecs(acc->getActiveCodecs()); jami::Manager::instance().saveConfig(acc); } } #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) void addVideoDevice(const std::string& node, const std::vector<std::map<std::string, std::string>>& devInfo) { jami::Manager::instance().getVideoManager().videoDeviceMonitor.addDevice(node, devInfo); } void removeVideoDevice(const std::string& node) { jami::Manager::instance().getVideoManager().videoDeviceMonitor.removeDevice(node); } #endif } // namespace libjami namespace jami { #ifdef ENABLE_VIDEO video::VideoDeviceMonitor& getVideoDeviceMonitor() { return Manager::instance().getVideoManager().videoDeviceMonitor; } std::shared_ptr<video::VideoInput> getVideoInput(const std::string& resource, video::VideoInputMode inputMode, const std::string& sink) { auto sinkId = sink.empty() ? resource : sink; auto& vmgr = Manager::instance().getVideoManager(); std::lock_guard lk(vmgr.videoMutex); auto it = vmgr.videoInputs.find(sinkId); if (it != vmgr.videoInputs.end()) { if (auto input = it->second.lock()) { return input; } } auto input = std::make_shared<video::VideoInput>(inputMode, resource, sinkId); vmgr.videoInputs[sinkId] = input; return input; } void VideoManager::setDeviceOrientation(const std::string& deviceId, int angle) { videoDeviceMonitor.setDeviceOrientation(deviceId, angle); } #endif std::shared_ptr<AudioInput> getAudioInput(const std::string& device) { auto& vmgr = Manager::instance().getVideoManager(); std::lock_guard lk(vmgr.audioMutex); // erase expired audio inputs for (auto it = vmgr.audioInputs.cbegin(); it != vmgr.audioInputs.cend();) { if (it->second.expired()) it = vmgr.audioInputs.erase(it); else ++it; } auto it = vmgr.audioInputs.find(device); if (it != vmgr.audioInputs.end()) { if (auto input = it->second.lock()) { return input; } } auto input = std::make_shared<AudioInput>(device); vmgr.audioInputs[device] = input; return input; } bool VideoManager::hasRunningPlayers() { auto& vmgr = Manager::instance().getVideoManager(); return !vmgr.mediaPlayers.empty(); } std::shared_ptr<MediaPlayer> getMediaPlayer(const std::string& id) { auto& vmgr = Manager::instance().getVideoManager(); auto it = vmgr.mediaPlayers.find(id); if (it != vmgr.mediaPlayers.end()) { return it->second; } return {}; } std::string createMediaPlayer(const std::string& path) { auto player = getMediaPlayer(path); if (!player) { player = std::make_shared<MediaPlayer>(path); } else { return path; } Manager::instance().getVideoManager().mediaPlayers[path] = player; return path; } bool pausePlayer(const std::string& id, bool pause) { if (auto player = getMediaPlayer(id)) { player->pause(pause); return true; } return false; } bool closeMediaPlayer(const std::string& id) { return Manager::instance().getVideoManager().mediaPlayers.erase(id) > 0; } bool mutePlayerAudio(const std::string& id, bool mute) { if (auto player = getMediaPlayer(id)) { player->muteAudio(mute); return true; } return false; } bool playerSeekToTime(const std::string& id, int time) { if (auto player = getMediaPlayer(id)) return player->seekToTime(time); return false; } int64_t getPlayerPosition(const std::string& id) { if (auto player = getMediaPlayer(id)) return player->getPlayerPosition(); return -1; } int64_t getPlayerDuration(const std::string& id) { if (auto player = getMediaPlayer(id)) return player->getPlayerDuration(); return -1; } void setAutoRestart(const std::string& id, bool restart) { if (auto player = getMediaPlayer(id)) player->setAutoRestart(restart); } } // namespace jami
21,238
C++
.cpp
731
24.280438
101
0.653782
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,845
plugin_manager_interface.cpp
savoirfairelinux_jami-daemon/src/client/plugin_manager_interface.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "plugin_manager_interface.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef ENABLE_PLUGIN #include "manager.h" #include "plugin/jamipluginmanager.h" #endif namespace libjami { bool loadPlugin(const std::string& path) { #ifdef ENABLE_PLUGIN bool status = jami::Manager::instance().getJamiPluginManager().loadPlugin(path); jami::Manager::instance().pluginPreferences.saveStateLoadedPlugins(path, status); jami::Manager::instance().saveConfig(); return status; #endif return false; } bool unloadPlugin(const std::string& path) { #ifdef ENABLE_PLUGIN bool status = jami::Manager::instance().getJamiPluginManager().unloadPlugin(path); jami::Manager::instance().pluginPreferences.saveStateLoadedPlugins(path, false); jami::Manager::instance().saveConfig(); return status; #endif return false; } std::map<std::string, std::string> getPluginDetails(const std::string& path) { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().getPluginDetails(path); #endif return {}; } std::vector<std::map<std::string, std::string>> getPluginPreferences(const std::string& path, const std::string& accountId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().getPluginPreferences(path, accountId); #endif return {}; } bool setPluginPreference(const std::string& path, const std::string& accountId, const std::string& key, const std::string& value) { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().setPluginPreference(path, accountId, key, value); #endif return {}; } std::map<std::string, std::string> getPluginPreferencesValues(const std::string& path, const std::string& accountId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().getPluginPreferencesValuesMap(path, accountId); #endif return {}; } bool resetPluginPreferencesValues(const std::string& path, const std::string& accountId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .resetPluginPreferencesValuesMap(path, accountId); #endif } std::vector<std::string> getInstalledPlugins() { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().getInstalledPlugins(); #endif return {}; } std::vector<std::string> getLoadedPlugins() { #ifdef ENABLE_PLUGIN return jami::Manager::instance().pluginPreferences.getLoadedPlugins(); #endif return {}; } int installPlugin(const std::string& jplPath, bool force) { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().installPlugin(jplPath, force); #endif return -1; } int uninstallPlugin(const std::string& pluginRootPath) { #ifdef ENABLE_PLUGIN int status = jami::Manager::instance().getJamiPluginManager().uninstallPlugin(pluginRootPath); jami::Manager::instance().pluginPreferences.saveStateLoadedPlugins(pluginRootPath, false); jami::Manager::instance().saveConfig(); return status; #endif return -1; } std::map<std::string, std::string> getPlatformInfo() { #ifdef ENABLE_PLUGIN return jami::Manager::instance().getJamiPluginManager().getPlatformInfo(); #endif return {}; } std::vector<std::string> getCallMediaHandlers() { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .getCallMediaHandlers(); #endif return {}; } std::vector<std::string> getChatHandlers() { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getChatServicesManager() .getChatHandlers(); #endif return {}; } void toggleCallMediaHandler(const std::string& mediaHandlerId, const std::string& callId, bool toggle) { #ifdef ENABLE_PLUGIN jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .toggleCallMediaHandler(mediaHandlerId, callId, toggle); #endif } void toggleChatHandler(const std::string& chatHandlerId, const std::string& accountId, const std::string& peerId, bool toggle) { #ifdef ENABLE_PLUGIN jami::Manager::instance() .getJamiPluginManager() .getChatServicesManager() .toggleChatHandler(chatHandlerId, accountId, peerId, toggle); #endif } std::map<std::string, std::string> getCallMediaHandlerDetails(const std::string& mediaHandlerId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .getCallMediaHandlerDetails(mediaHandlerId); #endif return {}; } std::vector<std::string> getCallMediaHandlerStatus(const std::string& callId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getCallServicesManager() .getCallMediaHandlerStatus(callId); #endif return {}; } std::map<std::string, std::string> getChatHandlerDetails(const std::string& chatHandlerId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getChatServicesManager() .getChatHandlerDetails(chatHandlerId); #endif return {}; } std::vector<std::string> getChatHandlerStatus(const std::string& accountId, const std::string& peerId) { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getChatServicesManager() .getChatHandlerStatus(accountId, peerId); #endif return {}; } bool getPluginsEnabled() { #ifdef ENABLE_PLUGIN return jami::Manager::instance().pluginPreferences.getPluginsEnabled(); #endif return false; } void setPluginsEnabled(bool state) { #ifdef ENABLE_PLUGIN jami::Manager::instance().pluginPreferences.setPluginsEnabled(state); for (auto& item : jami::Manager::instance().pluginPreferences.getLoadedPlugins()) { if (state) jami::Manager::instance().getJamiPluginManager().loadPlugin(item); else jami::Manager::instance().getJamiPluginManager().unloadPlugin(item); } jami::Manager::instance().saveConfig(); #endif } void sendWebViewMessage(const std::string& pluginId, const std::string& webViewId, const std::string& messageId, const std::string& payload) { #ifdef ENABLE_PLUGIN jami::Manager::instance() .getJamiPluginManager() .getWebViewServicesManager() .sendWebViewMessage(pluginId, webViewId, messageId, payload); #endif } std::string sendWebViewAttach(const std::string& pluginId, const std::string& accountId, const std::string& webViewId, const std::string& action) { #ifdef ENABLE_PLUGIN return jami::Manager::instance() .getJamiPluginManager() .getWebViewServicesManager() .sendWebViewAttach(pluginId, accountId, webViewId, action); #endif } void sendWebViewDetach(const std::string& pluginId, const std::string& webViewId) { #ifdef ENABLE_PLUGIN jami::Manager::instance() .getJamiPluginManager() .getWebViewServicesManager() .sendWebViewDetach(pluginId, webViewId); #endif } } // namespace libjami
8,364
C++
.cpp
285
24.350877
101
0.696273
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,846
conversation_interface.cpp
savoirfairelinux_jami-daemon/src/client/conversation_interface.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "conversation_interface.h" #include <cerrno> #include <sstream> #include <cstring> #include "logger.h" #include "manager.h" #include "jamidht/jamiaccount.h" #include "jamidht/conversation_module.h" namespace libjami { std::string startConversation(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->startConversation(); return {}; } void acceptConversationRequest(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) convModule->acceptConversationRequest(conversationId); } void declineConversationRequest(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) acc->declineConversationRequest(conversationId); } bool removeConversation(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->removeConversation(conversationId); return false; } std::vector<std::string> getConversations(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->getConversations(); return {}; } std::vector<std::map<std::string, std::string>> getActiveCalls(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->getActiveCalls(conversationId); return {}; } std::vector<std::map<std::string, std::string>> getConversationRequests(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->getConversationRequests(); return {}; } void updateConversationInfos(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& infos) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) convModule->updateConversationInfos(conversationId, infos); } std::map<std::string, std::string> conversationInfos(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->conversationInfos(conversationId); return {}; } void setConversationPreferences(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& prefs) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) convModule->setConversationPreferences(conversationId, prefs); } std::map<std::string, std::string> getConversationPreferences(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->getConversationPreferences(conversationId); return {}; } // Member management void addConversationMember(const std::string& accountId, const std::string& conversationId, const std::string& contactUri) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) { dht::InfoHash h(contactUri); if (not h) { JAMI_ERROR("addConversationMember: invalid contact URI `{}`", contactUri); return; } convModule->addConversationMember(conversationId, h); } } void removeConversationMember(const std::string& accountId, const std::string& conversationId, const std::string& contactUri) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) { dht::InfoHash h(contactUri); if (not h) { JAMI_ERROR("removeConversationMember: invalid contact URI `{}`", contactUri); return; } convModule->removeConversationMember(conversationId, h); } } std::vector<std::map<std::string, std::string>> getConversationMembers(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->getConversationMembers(conversationId, true); return {}; } // Message send/load void sendMessage(const std::string& accountId, const std::string& conversationId, const std::string& message, const std::string& commitId, const int32_t& flag) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) { if (flag == 0 /* Reply or simple commit */) { convModule->sendMessage(conversationId, message, commitId); } else if (flag == 1 /* message edition */) { convModule->editMessage(conversationId, message, commitId); } else if (flag == 2 /* reaction */) { convModule->reactToMessage(conversationId, message, commitId); } } } uint32_t loadConversationMessages(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, size_t n) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->loadConversationMessages(conversationId, fromMessage, n); return 0; } uint32_t loadConversation(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, size_t n) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->loadConversation(conversationId, fromMessage, n); return 0; } uint32_t loadConversationUntil(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, const std::string& toMessage) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->loadConversationUntil(conversationId, fromMessage, toMessage); return 0; } uint32_t loadSwarmUntil(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, const std::string& toMessage) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->loadSwarmUntil(conversationId, fromMessage, toMessage); return 0; } uint32_t countInteractions(const std::string& accountId, const std::string& conversationId, const std::string& toId, const std::string& fromId, const std::string& authorUri) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->countInteractions(conversationId, toId, fromId, authorUri); return 0; } void clearCache(const std::string& accountId, const std::string& conversationId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) convModule->clearCache(conversationId); } uint32_t searchConversation(const std::string& accountId, const std::string& conversationId, const std::string& author, const std::string& lastId, const std::string& regexSearch, const std::string& type, const int64_t& after, const int64_t& before, const uint32_t& maxResult, const int32_t& flag) { uint32_t res = 0; jami::Filter filter {author, lastId, regexSearch, type, after, before, maxResult, flag != 0}; for (const auto& accId : jami::Manager::instance().getAccountList()) { if (!accountId.empty() && accId != accountId) continue; if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accId)) { res = std::uniform_int_distribution<uint32_t>()(acc->rand); if (auto convModule = acc->convModule(true)) { convModule->search(res, conversationId, filter); } } } return res; } void reloadConversationsAndRequests(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { acc->reloadContacts(); if (auto convModule = acc->convModule(true)) { convModule->reloadRequests(); convModule->loadConversations(); } } } } // namespace libjami
11,060
C++
.cpp
274
33
97
0.65799
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,847
ring_signal.cpp
savoirfairelinux_jami-daemon/src/client/ring_signal.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ring_signal.h" namespace jami { SignalHandlerMap& getSignalHandlers() { static SignalHandlerMap handlers = { /* Call */ exported_callback<libjami::CallSignal::StateChange>(), exported_callback<libjami::CallSignal::TransferFailed>(), exported_callback<libjami::CallSignal::TransferSucceeded>(), exported_callback<libjami::CallSignal::RecordPlaybackStopped>(), exported_callback<libjami::CallSignal::VoiceMailNotify>(), exported_callback<libjami::CallSignal::IncomingMessage>(), exported_callback<libjami::CallSignal::IncomingCall>(), exported_callback<libjami::CallSignal::IncomingCallWithMedia>(), exported_callback<libjami::CallSignal::MediaChangeRequested>(), exported_callback<libjami::CallSignal::RecordPlaybackFilepath>(), exported_callback<libjami::CallSignal::ConferenceCreated>(), exported_callback<libjami::CallSignal::ConferenceChanged>(), exported_callback<libjami::CallSignal::UpdatePlaybackScale>(), exported_callback<libjami::CallSignal::ConferenceRemoved>(), exported_callback<libjami::CallSignal::RecordingStateChanged>(), exported_callback<libjami::CallSignal::RtcpReportReceived>(), exported_callback<libjami::CallSignal::PeerHold>(), exported_callback<libjami::CallSignal::VideoMuted>(), exported_callback<libjami::CallSignal::AudioMuted>(), exported_callback<libjami::CallSignal::SmartInfo>(), exported_callback<libjami::CallSignal::ConnectionUpdate>(), exported_callback<libjami::CallSignal::OnConferenceInfosUpdated>(), exported_callback<libjami::CallSignal::RemoteRecordingChanged>(), exported_callback<libjami::CallSignal::MediaNegotiationStatus>(), /* Configuration */ exported_callback<libjami::ConfigurationSignal::VolumeChanged>(), exported_callback<libjami::ConfigurationSignal::AccountsChanged>(), exported_callback<libjami::ConfigurationSignal::AccountDetailsChanged>(), exported_callback<libjami::ConfigurationSignal::StunStatusFailed>(), exported_callback<libjami::ConfigurationSignal::RegistrationStateChanged>(), exported_callback<libjami::ConfigurationSignal::VolatileDetailsChanged>(), exported_callback<libjami::ConfigurationSignal::CertificatePinned>(), exported_callback<libjami::ConfigurationSignal::CertificatePathPinned>(), exported_callback<libjami::ConfigurationSignal::CertificateExpired>(), exported_callback<libjami::ConfigurationSignal::CertificateStateChanged>(), exported_callback<libjami::ConfigurationSignal::IncomingAccountMessage>(), exported_callback<libjami::ConfigurationSignal::ComposingStatusChanged>(), exported_callback<libjami::ConfigurationSignal::AccountMessageStatusChanged>(), exported_callback<libjami::ConfigurationSignal::NeedsHost>(), exported_callback<libjami::ConfigurationSignal::ActiveCallsChanged>(), exported_callback<libjami::ConfigurationSignal::ProfileReceived>(), exported_callback<libjami::ConfigurationSignal::IncomingTrustRequest>(), exported_callback<libjami::ConfigurationSignal::ContactAdded>(), exported_callback<libjami::ConfigurationSignal::ContactRemoved>(), exported_callback<libjami::ConfigurationSignal::ExportOnRingEnded>(), exported_callback<libjami::ConfigurationSignal::KnownDevicesChanged>(), exported_callback<libjami::ConfigurationSignal::NameRegistrationEnded>(), exported_callback<libjami::ConfigurationSignal::RegisteredNameFound>(), exported_callback<libjami::ConfigurationSignal::UserSearchEnded>(), exported_callback<libjami::ConfigurationSignal::MediaParametersChanged>(), exported_callback<libjami::ConfigurationSignal::MigrationEnded>(), exported_callback<libjami::ConfigurationSignal::DeviceRevocationEnded>(), exported_callback<libjami::ConfigurationSignal::AccountProfileReceived>(), exported_callback<libjami::ConfigurationSignal::Error>(), #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) exported_callback<libjami::ConfigurationSignal::GetHardwareAudioFormat>(), #endif #if defined(__ANDROID__) || (defined(TARGET_OS_IOS) && TARGET_OS_IOS) exported_callback<libjami::ConfigurationSignal::GetAppDataPath>(), exported_callback<libjami::ConfigurationSignal::GetDeviceName>(), #endif exported_callback<libjami::ConfigurationSignal::HardwareDecodingChanged>(), exported_callback<libjami::ConfigurationSignal::HardwareEncodingChanged>(), exported_callback<libjami::ConfigurationSignal::MessageSend>(), /* Presence */ exported_callback<libjami::PresenceSignal::NewServerSubscriptionRequest>(), exported_callback<libjami::PresenceSignal::NearbyPeerNotification>(), exported_callback<libjami::PresenceSignal::ServerError>(), exported_callback<libjami::PresenceSignal::NewBuddyNotification>(), exported_callback<libjami::PresenceSignal::SubscriptionStateChanged>(), /* Audio */ exported_callback<libjami::AudioSignal::DeviceEvent>(), exported_callback<libjami::AudioSignal::AudioMeter>(), /* DataTransfer */ exported_callback<libjami::DataTransferSignal::DataTransferEvent>(), #ifdef ENABLE_VIDEO /* MediaPlayer */ exported_callback<libjami::MediaPlayerSignal::FileOpened>(), /* Video */ exported_callback<libjami::VideoSignal::DeviceEvent>(), exported_callback<libjami::VideoSignal::DecodingStarted>(), exported_callback<libjami::VideoSignal::DecodingStopped>(), #ifdef __ANDROID__ exported_callback<libjami::VideoSignal::GetCameraInfo>(), exported_callback<libjami::VideoSignal::SetParameters>(), exported_callback<libjami::VideoSignal::RequestKeyFrame>(), exported_callback<libjami::VideoSignal::SetBitrate>(), #endif exported_callback<libjami::VideoSignal::StartCapture>(), exported_callback<libjami::VideoSignal::StopCapture>(), exported_callback<libjami::VideoSignal::DeviceAdded>(), exported_callback<libjami::VideoSignal::ParametersChanged>(), #endif /* Conversation */ exported_callback<libjami::ConversationSignal::ConversationLoaded>(), exported_callback<libjami::ConversationSignal::SwarmLoaded>(), exported_callback<libjami::ConversationSignal::MessagesFound>(), exported_callback<libjami::ConversationSignal::MessageReceived>(), exported_callback<libjami::ConversationSignal::SwarmMessageReceived>(), exported_callback<libjami::ConversationSignal::SwarmMessageUpdated>(), exported_callback<libjami::ConversationSignal::ReactionAdded>(), exported_callback<libjami::ConversationSignal::ReactionRemoved>(), exported_callback<libjami::ConversationSignal::ConversationProfileUpdated>(), exported_callback<libjami::ConversationSignal::ConversationRequestReceived>(), exported_callback<libjami::ConversationSignal::ConversationRequestDeclined>(), exported_callback<libjami::ConversationSignal::ConversationReady>(), exported_callback<libjami::ConversationSignal::ConversationRemoved>(), exported_callback<libjami::ConversationSignal::ConversationMemberEvent>(), exported_callback<libjami::ConversationSignal::ConversationSyncFinished>(), exported_callback<libjami::ConversationSignal::ConversationCloned>(), exported_callback<libjami::ConversationSignal::CallConnectionRequest>(), exported_callback<libjami::ConversationSignal::OnConversationError>(), exported_callback<libjami::ConversationSignal::ConversationPreferencesUpdated>(), #ifdef ENABLE_PLUGIN exported_callback<libjami::PluginSignal::WebViewMessageReceived>(), #endif }; return handlers; } }; // namespace jami namespace libjami { void registerSignalHandlers(const std::map<std::string, std::shared_ptr<CallbackWrapperBase>>& handlers) { auto& handlers_ = jami::getSignalHandlers(); for (auto& item : handlers) { auto iter = handlers_.find(item.first); if (iter == handlers_.end()) { JAMI_ERR("Signal %s not supported", item.first.c_str()); continue; } iter->second = item.second; } } void unregisterSignalHandlers() { auto& handlers_ = jami::getSignalHandlers(); for (auto& item : handlers_) { item.second = {}; } } } // namespace libjami
9,336
C++
.cpp
166
49.289157
99
0.737682
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,848
configurationmanager.cpp
savoirfairelinux_jami-daemon/src/client/configurationmanager.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "configurationmanager_interface.h" #include "account_schema.h" #include "manager.h" #include "logger.h" #include "fileutils.h" #include "archiver.h" #include "sip/sipaccount.h" #include "jamidht/jamiaccount.h" #include "sip/sipaccount_config.h" #include "jamidht/jamiaccount_config.h" #include "audio/audiolayer.h" #include "system_codec_container.h" #include "account_const.h" #include "client/ring_signal.h" #include "audio/ringbufferpool.h" #include "connectivity/security/tlsvalidator.h" #include <dhtnet/ip_utils.h> #include <dhtnet/upnp/upnp_context.h> #include <dhtnet/certstore.h> #ifdef __APPLE__ #include <TargetConditionals.h> #endif #ifdef _MSC_VER #include "windirent.h" #else #include <dirent.h> #endif #include <cerrno> #include <cstring> #include <sstream> #ifdef _WIN32 #undef interface #endif namespace libjami { constexpr unsigned CODECS_NOT_LOADED = 0x1000; /** Codecs not found */ using jami::SIPAccount; using jami::JamiAccount; using jami::tls::TlsValidator; using jami::AudioDeviceType; void registerConfHandlers(const std::map<std::string, std::shared_ptr<CallbackWrapperBase>>& handlers) { registerSignalHandlers(handlers); } std::map<std::string, std::string> getAccountDetails(const std::string& accountId) { return jami::Manager::instance().getAccountDetails(accountId); } std::map<std::string, std::string> getVolatileAccountDetails(const std::string& accountId) { return jami::Manager::instance().getVolatileAccountDetails(accountId); } std::map<std::string, std::string> validateCertificate(const std::string& accountId, const std::string& certificate) { try { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return TlsValidator {acc->certStore(), acc->certStore().getCertificate(certificate)} .getSerializedChecks(); } catch (const std::runtime_error& e) { JAMI_WARN("Certificate loading failed: %s", e.what()); } return {{Certificate::ChecksNames::EXIST, Certificate::CheckValuesNames::FAILED}}; } std::map<std::string, std::string> validateCertificatePath(const std::string& accountId, const std::string& certificate, const std::string& privateKey, const std::string& privateKeyPass, const std::string& caList) { try { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return TlsValidator {acc->certStore(), certificate, privateKey, privateKeyPass, caList} .getSerializedChecks(); } catch (const std::runtime_error& e) { JAMI_WARN("Certificate loading failed: %s", e.what()); return {{Certificate::ChecksNames::EXIST, Certificate::CheckValuesNames::FAILED}}; } return {}; } std::map<std::string, std::string> getCertificateDetails(const std::string& accountId, const std::string& certificate) { try { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return TlsValidator {acc->certStore(), acc->certStore().getCertificate(certificate)} .getSerializedDetails(); } catch (const std::runtime_error& e) { JAMI_WARN("Certificate loading failed: %s", e.what()); } return {}; } std::map<std::string, std::string> getCertificateDetailsPath(const std::string& accountId, const std::string& certificate, const std::string& privateKey, const std::string& privateKeyPassword) { try { auto crt = std::make_shared<dht::crypto::Certificate>( jami::fileutils::loadFile(certificate)); if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { TlsValidator validator {acc->certStore(), certificate, privateKey, privateKeyPassword}; acc->certStore().pinCertificate(validator.getCertificate(), false); return validator.getSerializedDetails(); } } catch (const std::runtime_error& e) { JAMI_WARN("Certificate loading failed: %s", e.what()); } return {}; } std::vector<std::string> getPinnedCertificates(const std::string& accountId) { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->certStore().getPinnedCertificates(); return {}; } std::vector<std::string> pinCertificate(const std::string& accountId, const std::vector<uint8_t>& certificate, bool local) { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->certStore().pinCertificate(certificate, local); return {}; } void pinCertificatePath(const std::string& accountId, const std::string& path) { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) acc->certStore().pinCertificatePath(path); } bool unpinCertificate(const std::string& accountId, const std::string& certId) { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->certStore().unpinCertificate(certId); return {}; } unsigned unpinCertificatePath(const std::string& accountId, const std::string& path) { if (const auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->certStore().unpinCertificatePath(path); return {}; } bool pinRemoteCertificate(const std::string& accountId, const std::string& certId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { acc->dht()->findCertificate(dht::InfoHash(certId), [](const std::shared_ptr<dht::crypto::Certificate>& crt) {}); return true; } return false; } bool setCertificateStatus(const std::string& accountId, const std::string& certId, const std::string& ststr) { try { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { auto status = dhtnet::tls::TrustStore::statusFromStr(ststr.c_str()); return acc->setCertificateStatus(certId, status); } } catch (const std::out_of_range&) { } return false; } std::vector<std::string> getCertificatesByStatus(const std::string& accountId, const std::string& ststr) { auto status = dhtnet::tls::TrustStore::statusFromStr(ststr.c_str()); if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->getCertificatesByStatus(status); return {}; } void setAccountDetails(const std::string& accountId, const std::map<std::string, std::string>& details) { jami::Manager::instance().setAccountDetails(accountId, details); } void setAccountActive(const std::string& accountId, bool enable, bool shutdownConnections) { jami::Manager::instance().setAccountActive(accountId, enable, shutdownConnections); } void loadAccountAndConversation(const std::string& accountId, bool loadAll, const std::string& convId) { jami::Manager::instance().loadAccountAndConversation(accountId, loadAll, convId); } void sendRegister(const std::string& accountId, bool enable) { jami::Manager::instance().sendRegister(accountId, enable); } bool isPasswordValid(const std::string& accountId, const std::string& password) { if (auto acc = jami::Manager::instance().getAccount<JamiAccount>(accountId)) return acc->isPasswordValid(password); return false; } std::vector<uint8_t> getPasswordKey(const std::string& accountID, const std::string& password) { if (auto acc = jami::Manager::instance().getAccount<JamiAccount>(accountID)) return acc->getPasswordKey(password); return {}; } void registerAllAccounts() { jami::Manager::instance().registerAccounts(); } uint64_t sendAccountTextMessage(const std::string& accountId, const std::string& to, const std::map<std::string, std::string>& payloads, int32_t flags) { bool onlyConnected = flags & 0x1; return jami::Manager::instance().sendTextMessage(accountId, to, payloads, onlyConnected); } std::vector<Message> getLastMessages(const std::string& accountId, const uint64_t& base_timestamp) { if (const auto acc = jami::Manager::instance().getAccount(accountId)) return acc->getLastMessages(base_timestamp); return {}; } std::map<std::string, std::string> getNearbyPeers(const std::string& accountId) { return jami::Manager::instance().getNearbyPeers(accountId); } void updateProfile(const std::string& accountId,const std::string& displayName, const std::string& avatar,const uint64_t& flag) { jami::Manager::instance().updateProfile(accountId, displayName, avatar, flag); } int getMessageStatus(uint64_t messageId) { return jami::Manager::instance().getMessageStatus(messageId); } int getMessageStatus(const std::string& accountId, uint64_t messageId) { return jami::Manager::instance().getMessageStatus(accountId, messageId); } bool cancelMessage(const std::string& accountId, uint64_t messageId) { return {}; } void setIsComposing(const std::string& accountId, const std::string& conversationUri, bool isWriting) { if (const auto acc = jami::Manager::instance().getAccount(accountId)) acc->setIsComposing(conversationUri, isWriting); } bool setMessageDisplayed(const std::string& accountId, const std::string& conversationUri, const std::string& messageId, int status) { if (const auto acc = jami::Manager::instance().getAccount(accountId)) return acc->setMessageDisplayed(conversationUri, messageId, status); return false; } bool exportOnRing(const std::string& accountId, const std::string& password) { if (const auto account = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { account->addDevice(password); return true; } return false; } bool exportToFile(const std::string& accountId, const std::string& destinationPath, const std::string& scheme, const std::string& password) { if (const auto account = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { return account->exportArchive(destinationPath, scheme, password); } return false; } bool revokeDevice(const std::string& accountId, const std::string& deviceId, const std::string& scheme, const std::string& password) { if (const auto account = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { return account->revokeDevice(deviceId, scheme, password); } return false; } std::map<std::string, std::string> getKnownRingDevices(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->getKnownDevices(); return {}; } bool changeAccountPassword(const std::string& accountId, const std::string& password_old, const std::string& password_new) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->changeArchivePassword(password_old, password_new); return false; } /* contacts */ void addContact(const std::string& accountId, const std::string& uri) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->addContact(uri); } void removeContact(const std::string& accountId, const std::string& uri, bool ban) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->removeContact(uri, ban); } std::map<std::string, std::string> getContactDetails(const std::string& accountId, const std::string& uri) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->getContactDetails(uri); return {}; } std::vector<std::map<std::string, std::string>> getContacts(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->getContacts(); return {}; } /* contact requests */ std::vector<std::map<std::string, std::string>> getTrustRequests(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->getTrustRequests(); return {}; } bool acceptTrustRequest(const std::string& accountId, const std::string& from) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->acceptTrustRequest(from); return false; } bool discardTrustRequest(const std::string& accountId, const std::string& from) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) return acc->discardTrustRequest(from); return false; } void sendTrustRequest(const std::string& accountId, const std::string& to, const std::vector<uint8_t>& payload) { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) acc->sendTrustRequest(to, payload); } /// This function is used as a base for new accounts for clients that support it std::map<std::string, std::string> getAccountTemplate(const std::string& accountType) { if (accountType == Account::ProtocolNames::JAMI || accountType == Account::ProtocolNames::RING) return jami::JamiAccountConfig().toMap(); else if (accountType == Account::ProtocolNames::SIP) return jami::SipAccountConfig().toMap(); return {}; } std::string addAccount(const std::map<std::string, std::string>& details, const std::string& accountId) { return jami::Manager::instance().addAccount(details, accountId); } void monitor(bool continuous) { return jami::Manager::instance().monitor(continuous); } std::vector<std::map<std::string, std::string>> getConnectionList(const std::string& accountId, const std::string& conversationId) { return jami::Manager::instance().getConnectionList(accountId, conversationId); } std::vector<std::map<std::string, std::string>> getChannelList(const std::string& accountId, const std::string& connectionId) { return jami::Manager::instance().getChannelList(accountId, connectionId); } void removeAccount(const std::string& accountId) { return jami::Manager::instance().removeAccount(accountId, true); // with 'flush' enabled } std::vector<std::string> getAccountList() { return jami::Manager::instance().getAccountList(); } /** * Send the list of all codecs loaded to the client through DBus. * Can stay global, as only the active codecs will be set per accounts */ std::vector<unsigned> getCodecList() { std::vector<unsigned> list { jami::getSystemCodecContainer()->getSystemCodecInfoIdList(jami::MEDIA_ALL)}; if (list.empty()) jami::emitSignal<ConfigurationSignal::Error>(CODECS_NOT_LOADED); return list; } std::vector<std::string> getSupportedTlsMethod() { return SIPAccount::getSupportedTlsProtocols(); } std::vector<std::string> getSupportedCiphers(const std::string& accountId) { if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) return SIPAccount::getSupportedTlsCiphers(); JAMI_ERR("SIP account %s doesn't exist", accountId.c_str()); return {}; } bool setCodecDetails(const std::string& accountId, const unsigned& codecId, const std::map<std::string, std::string>& details) { auto acc = jami::Manager::instance().getAccount(accountId); if (!acc) { JAMI_ERR("Unable to find account %s. Unable to set codec details", accountId.c_str()); return false; } auto codec = acc->searchCodecById(codecId, jami::MEDIA_ALL); if (!codec) { JAMI_ERR("Unable to find codec %d", codecId); return false; } try { if (codec->mediaType & jami::MEDIA_AUDIO) { if (auto foundCodec = std::static_pointer_cast<jami::SystemAudioCodecInfo>(codec)) { foundCodec->setCodecSpecifications(details); jami::emitSignal<ConfigurationSignal::MediaParametersChanged>(accountId); return true; } } if (codec->mediaType & jami::MEDIA_VIDEO) { if (auto foundCodec = std::static_pointer_cast<jami::SystemVideoCodecInfo>(codec)) { foundCodec->setCodecSpecifications(details); JAMI_WARN("parameters for %s changed ", foundCodec->name.c_str()); if (auto call = jami::Manager::instance().getCurrentCall()) { if (call->getVideoCodec() == foundCodec) { JAMI_WARN("%s running. Need to restart encoding", foundCodec->name.c_str()); call->restartMediaSender(); } } jami::emitSignal<ConfigurationSignal::MediaParametersChanged>(accountId); return true; } } } catch (const std::exception& e) { JAMI_ERR("Unable to set codec specifications: %s", e.what()); } return false; } std::map<std::string, std::string> getCodecDetails(const std::string& accountId, const unsigned& codecId) { auto acc = jami::Manager::instance().getAccount(accountId); if (!acc) { JAMI_ERR("Unable to find account %s return default codec details", accountId.c_str()); return jami::Account::getDefaultCodecDetails(codecId); } auto codec = acc->searchCodecById(codecId, jami::MEDIA_ALL); if (!codec) { jami::emitSignal<ConfigurationSignal::Error>(CODECS_NOT_LOADED); return {}; } if (codec->mediaType & jami::MEDIA_AUDIO) if (auto foundCodec = std::static_pointer_cast<jami::SystemAudioCodecInfo>(codec)) return foundCodec->getCodecSpecifications(); if (codec->mediaType & jami::MEDIA_VIDEO) if (auto foundCodec = std::static_pointer_cast<jami::SystemVideoCodecInfo>(codec)) return foundCodec->getCodecSpecifications(); jami::emitSignal<ConfigurationSignal::Error>(CODECS_NOT_LOADED); return {}; } std::vector<unsigned> getActiveCodecList(const std::string& accountId) { if (auto acc = jami::Manager::instance().getAccount(accountId)) return acc->getActiveCodecs(); JAMI_ERR("Unable to find account %s, returning default", accountId.c_str()); return jami::Account::getDefaultCodecsId(); } void setActiveCodecList(const std::string& accountId, const std::vector<unsigned>& list) { if (auto acc = jami::Manager::instance().getAccount(accountId)) { acc->setActiveCodecs(list); jami::Manager::instance().saveConfig(acc); } else { JAMI_ERR("Unable to find account %s", accountId.c_str()); } } std::vector<std::string> getAudioPluginList() { return {PCM_DEFAULT, PCM_DMIX_DSNOOP}; } void setAudioPlugin(const std::string& audioPlugin) { return jami::Manager::instance().setAudioPlugin(audioPlugin); } std::vector<std::string> getAudioOutputDeviceList() { return jami::Manager::instance().getAudioOutputDeviceList(); } std::vector<std::string> getAudioInputDeviceList() { return jami::Manager::instance().getAudioInputDeviceList(); } void setAudioOutputDevice(int32_t index) { return jami::Manager::instance().setAudioDevice(index, AudioDeviceType::PLAYBACK); } void setAudioInputDevice(int32_t index) { return jami::Manager::instance().setAudioDevice(index, AudioDeviceType::CAPTURE); } void startAudio() { jami::Manager::instance().startAudio(); } void setAudioRingtoneDevice(int32_t index) { return jami::Manager::instance().setAudioDevice(index, AudioDeviceType::RINGTONE); } std::vector<std::string> getCurrentAudioDevicesIndex() { return jami::Manager::instance().getCurrentAudioDevicesIndex(); } int32_t getAudioInputDeviceIndex(const std::string& name) { return jami::Manager::instance().getAudioInputDeviceIndex(name); } int32_t getAudioOutputDeviceIndex(const std::string& name) { return jami::Manager::instance().getAudioOutputDeviceIndex(name); } std::string getCurrentAudioOutputPlugin() { auto plugin = jami::Manager::instance().getCurrentAudioOutputPlugin(); JAMI_DBG("Get audio plugin %s", plugin.c_str()); return plugin; } std::string getNoiseSuppressState() { return jami::Manager::instance().getNoiseSuppressState(); } void setNoiseSuppressState(const std::string& state) { jami::Manager::instance().setNoiseSuppressState(state); } bool isAgcEnabled() { return jami::Manager::instance().isAGCEnabled(); } void setAgcState(bool enabled) { jami::Manager::instance().setAGCState(enabled); } std::string getRecordPath() { return jami::Manager::instance().audioPreference.getRecordPath(); } void setRecordPath(const std::string& recPath) { jami::Manager::instance().audioPreference.setRecordPath(recPath); } bool getIsAlwaysRecording() { return jami::Manager::instance().getIsAlwaysRecording(); } void setIsAlwaysRecording(bool rec) { jami::Manager::instance().setIsAlwaysRecording(rec); } bool getRecordPreview() { #ifdef ENABLE_VIDEO return jami::Manager::instance().videoPreferences.getRecordPreview(); #else return false; #endif } void setRecordPreview(bool rec) { #ifdef ENABLE_VIDEO jami::Manager::instance().videoPreferences.setRecordPreview(rec); jami::Manager::instance().saveConfig(); #endif } int32_t getRecordQuality() { #ifdef ENABLE_VIDEO return jami::Manager::instance().videoPreferences.getRecordQuality(); #else return 0; #endif } void setRecordQuality(int32_t quality) { #ifdef ENABLE_VIDEO jami::Manager::instance().videoPreferences.setRecordQuality(quality); jami::Manager::instance().saveConfig(); #endif } int32_t getHistoryLimit() { return jami::Manager::instance().getHistoryLimit(); } void setHistoryLimit(int32_t days) { jami::Manager::instance().setHistoryLimit(days); } int32_t getRingingTimeout() { return jami::Manager::instance().getRingingTimeout(); } void setRingingTimeout(int32_t timeout) { jami::Manager::instance().setRingingTimeout(timeout); } std::vector<std::string> getSupportedAudioManagers() { return jami::AudioPreference::getSupportedAudioManagers(); } bool setAudioManager(const std::string& api) { return jami::Manager::instance().setAudioManager(api); } std::string getAudioManager() { return jami::Manager::instance().getAudioManager(); } void setVolume(const std::string& device, double value) { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) { JAMI_DBG("set volume for %s: %f", device.c_str(), value); if (device == "speaker") audiolayer->setPlaybackGain(value); else if (device == "mic") audiolayer->setCaptureGain(value); jami::emitSignal<ConfigurationSignal::VolumeChanged>(device, value); } else { JAMI_ERR("Audio layer not valid while updating volume"); } } double getVolume(const std::string& device) { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) { if (device == "speaker") return audiolayer->getPlaybackGain(); if (device == "mic") return audiolayer->getCaptureGain(); } JAMI_ERR("Audio layer not valid while updating volume"); return 0.0; } // FIXME: we should store "muteDtmf" instead of "playDtmf" // in config and avoid negating like this bool isDtmfMuted() { return not jami::Manager::instance().voipPreferences.getPlayDtmf(); } void muteDtmf(bool mute) { jami::Manager::instance().voipPreferences.setPlayDtmf(not mute); } bool isCaptureMuted() { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) return audiolayer->isCaptureMuted(); JAMI_ERR("Audio layer not valid"); return false; } void muteCapture(bool mute) { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) return audiolayer->muteCapture(mute); JAMI_ERR("Audio layer not valid"); return; } bool isPlaybackMuted() { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) return audiolayer->isPlaybackMuted(); JAMI_ERR("Audio layer not valid"); return false; } void mutePlayback(bool mute) { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) return audiolayer->mutePlayback(mute); JAMI_ERR("Audio layer not valid"); return; } bool isRingtoneMuted() { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) return audiolayer->isRingtoneMuted(); JAMI_ERR("Audio layer not valid"); return false; } void muteRingtone(bool mute) { if (auto audiolayer = jami::Manager::instance().getAudioDriver()) return audiolayer->muteRingtone(mute); JAMI_ERR("Audio layer not valid"); return; } void setAccountsOrder(const std::string& order) { jami::Manager::instance().setAccountsOrder(order); } std::string getAddrFromInterfaceName(const std::string& interface) { return dhtnet::ip_utils::getInterfaceAddr(interface, AF_INET); } std::vector<std::string> getAllIpInterface() { return dhtnet::ip_utils::getAllIpInterface(); } std::vector<std::string> getAllIpInterfaceByName() { return dhtnet::ip_utils::getAllIpInterfaceByName(); } std::vector<std::map<std::string, std::string>> getCredentials(const std::string& accountId) { if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) return sipaccount->getCredentials(); return {}; } void setCredentials(const std::string& accountId, const std::vector<std::map<std::string, std::string>>& details) { if (auto sipaccount = jami::Manager::instance().getAccount<SIPAccount>(accountId)) { sipaccount->doUnregister([&](bool /* transport_free */) { sipaccount->editConfig( [&](jami::SipAccountConfig& config) { config.setCredentials(details); }); sipaccount->loadConfig(); if (sipaccount->isEnabled()) sipaccount->doRegister(); }); jami::Manager::instance().saveConfig(sipaccount); } } void connectivityChanged() { JAMI_WARN("received connectivity changed - attempting to re-connect enabled accounts"); // reset the UPnP context #if !(defined(TARGET_OS_IOS) && TARGET_OS_IOS) try { jami::Manager::instance().upnpContext()->connectivityChanged(); } catch (std::runtime_error& e) { JAMI_ERR("UPnP context error: %s", e.what()); } #endif for (const auto& account : jami::Manager::instance().getAllAccounts()) { account->connectivityChanged(); } } bool lookupName(const std::string& account, const std::string& nameserver, const std::string& name) { #if HAVE_RINGNS if (account.empty()) { auto cb = [name](const std::string& result, jami::NameDirectory::Response response) { jami::emitSignal<libjami::ConfigurationSignal::RegisteredNameFound>("", (int) response, result, name); }; if (nameserver.empty()) jami::NameDirectory::lookupUri(name, "", cb); else jami::NameDirectory::instance(nameserver).lookupName(name, cb); return true; } else if (auto acc = jami::Manager::instance().getAccount<JamiAccount>(account)) { acc->lookupName(name); return true; } #endif return false; } bool lookupAddress(const std::string& account, const std::string& nameserver, const std::string& address) { #if HAVE_RINGNS if (account.empty()) { jami::NameDirectory::instance(nameserver) .lookupAddress(address, [address](const std::string& result, jami::NameDirectory::Response response) { jami::emitSignal<libjami::ConfigurationSignal::RegisteredNameFound>( "", (int) response, address, result); }); return true; } else if (auto acc = jami::Manager::instance().getAccount<JamiAccount>(account)) { acc->lookupAddress(address); return true; } #endif return false; } bool searchUser(const std::string& account, const std::string& query) { if (auto acc = jami::Manager::instance().getAccount<JamiAccount>(account)) { return acc->searchUser(query); } return false; } bool registerName(const std::string& account, const std::string& name, const std::string& scheme, const std::string& password) { #if HAVE_RINGNS if (auto acc = jami::Manager::instance().getAccount<JamiAccount>(account)) { acc->registerName(name, scheme, password); return true; } #endif return false; } void setPushNotificationToken(const std::string& token) { for (const auto& account : jami::Manager::instance().getAllAccounts()) { account->setPushNotificationToken(token); } } void setPushNotificationTopic(const std::string& topic) { for (const auto& account : jami::Manager::instance().getAllAccounts()) { account->setPushNotificationTopic(topic); } } void setPushNotificationConfig(const std::map<std::string, std::string>& data) { for (const auto& account : jami::Manager::instance().getAllAccounts()) { account->setPushNotificationConfig(data); } } void pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data) { try { auto it = data.find("to"); if (it != data.end()) { if (auto account = jami::Manager::instance().getAccount<JamiAccount>(it->second)) account->pushNotificationReceived(from, data); } #if defined(__ANDROID__) || defined(ANDROID) || defined(__Apple__) else { for (const auto& sipAccount : jami::Manager::instance().getAllAccounts<SIPAccount>()) { sipAccount->pushNotificationReceived(from, data); } } #endif } catch (const std::exception& e) { JAMI_ERR("Error processing push notification: %s", e.what()); } } bool isAudioMeterActive(const std::string& id) { return jami::Manager::instance().getRingBufferPool().isAudioMeterActive(id); } void setAudioMeterState(const std::string& id, bool state) { jami::Manager::instance().getRingBufferPool().setAudioMeterState(id, state); } void setDefaultModerator(const std::string& accountId, const std::string& peerURI, bool state) { jami::Manager::instance().setDefaultModerator(accountId, peerURI, state); } std::vector<std::string> getDefaultModerators(const std::string& accountId) { return jami::Manager::instance().getDefaultModerators(accountId); } void enableLocalModerators(const std::string& accountId, bool isModEnabled) { jami::Manager::instance().enableLocalModerators(accountId, isModEnabled); } bool isLocalModeratorsEnabled(const std::string& accountId) { return jami::Manager::instance().isLocalModeratorsEnabled(accountId); } void setAllModerators(const std::string& accountId, bool allModerators) { jami::Manager::instance().setAllModerators(accountId, allModerators); } bool isAllModerators(const std::string& accountId) { return jami::Manager::instance().isAllModerators(accountId); } void setResourceDirPath(const std::string& resourceDir) { jami::fileutils::set_resource_dir_path(resourceDir); } } // namespace libjami
32,778
C++
.cpp
1,014
27.685404
122
0.694727
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
751,849
datatransfer.cpp
savoirfairelinux_jami-daemon/src/client/datatransfer.cpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "datatransfer_interface.h" #include "manager.h" #include "data_transfer.h" #include "client/ring_signal.h" #include "jamidht/jamiaccount.h" namespace libjami { void registerDataXferHandlers(const std::map<std::string, std::shared_ptr<CallbackWrapperBase>>& handlers) { registerSignalHandlers(handlers); } void sendFile(const std::string& accountId, const std::string& conversationId, const std::string& path, const std::string& displayName, const std::string& replyTo) noexcept { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { acc->sendFile(conversationId, path, displayName, replyTo); } } bool downloadFile(const std::string& accountId, const std::string& conversationId, const std::string& interactionId, const std::string& fileId, const std::string& path) noexcept { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) if (auto convModule = acc->convModule(true)) return convModule->downloadFile(conversationId, interactionId, fileId, path); return {}; } DataTransferError cancelDataTransfer(const std::string& accountId, const std::string& conversationId, const std::string& fileId) noexcept { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { if (auto dt = acc->dataTransfer(conversationId)) return dt->cancel(fileId) ? libjami::DataTransferError::success : libjami::DataTransferError::invalid_argument; } return libjami::DataTransferError::invalid_argument; } DataTransferError fileTransferInfo(const std::string& accountId, const std::string& conversationId, const std::string& fileId, std::string& path, int64_t& total, int64_t& progress) noexcept { if (auto acc = jami::Manager::instance().getAccount<jami::JamiAccount>(accountId)) { if (auto dt = acc->dataTransfer(conversationId)) return dt->info(fileId, path, total, progress) ? libjami::DataTransferError::success : libjami::DataTransferError::invalid_argument; } return libjami::DataTransferError::invalid_argument; } } // namespace libjami
3,151
C++
.cpp
79
33.43038
101
0.680379
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,850
dbuspluginmanagerinterface.hpp
savoirfairelinux_jami-daemon/bin/dbus/dbuspluginmanagerinterface.hpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "dbuspluginmanagerinterface.adaptor.h" #include <plugin_manager_interface.h> class DBusPluginManagerInterface : public sdbus::AdaptorInterfaces<cx::ring::Ring::PluginManagerInterface_adaptor> { public: DBusPluginManagerInterface(sdbus::IConnection& connection) : AdaptorInterfaces(connection, "/cx/ring/Ring/PluginManagerInterface") { registerAdaptor(); registerSignalHandlers(); } ~DBusPluginManagerInterface() { unregisterAdaptor(); } bool loadPlugin(const std::string& path) { return libjami::loadPlugin(path); } bool unloadPlugin(const std::string& path) { return libjami::unloadPlugin(path); } std::map<std::string, std::string> getPluginDetails(const std::string& path) { return libjami::getPluginDetails(path); } std::vector<std::map<std::string, std::string>> getPluginPreferences(const std::string& path, const std::string& accountId) { return libjami::getPluginPreferences(path, accountId); } bool setPluginPreference(const std::string& path, const std::string& accountId, const std::string& key, const std::string& value) { return libjami::setPluginPreference(path, accountId, key, value); } std::map<std::string, std::string> getPluginPreferencesValues(const std::string& path, const std::string& accountId) { return libjami::getPluginPreferencesValues(path, accountId); } bool resetPluginPreferencesValues(const std::string& path, const std::string& accountId) { return libjami::resetPluginPreferencesValues(path, accountId); } std::map<std::string, std::string> getPlatformInfo() { return libjami::getPlatformInfo(); } auto getInstalledPlugins() -> decltype(libjami::getInstalledPlugins()) { return libjami::getInstalledPlugins(); } auto getLoadedPlugins() -> decltype(libjami::getLoadedPlugins()) { return libjami::getLoadedPlugins(); } int installPlugin(const std::string& jplPath, const bool& force) { return libjami::installPlugin(jplPath, force); } int uninstallPlugin(const std::string& pluginRootPath) { return libjami::uninstallPlugin(pluginRootPath); } auto getCallMediaHandlers() -> decltype(libjami::getCallMediaHandlers()) { return libjami::getCallMediaHandlers(); } auto getChatHandlers() -> decltype(libjami::getChatHandlers()) { return libjami::getChatHandlers(); } void toggleCallMediaHandler(const std::string& mediaHandlerId, const std::string& callId, const bool& toggle) { libjami::toggleCallMediaHandler(mediaHandlerId, callId, toggle); } void toggleChatHandler(const std::string& chatHandlerId, const std::string& accountId, const std::string& peerId, const bool& toggle) { libjami::toggleChatHandler(chatHandlerId, accountId, peerId, toggle); } std::map<std::string, std::string> getCallMediaHandlerDetails(const std::string& mediaHanlderId) { return libjami::getCallMediaHandlerDetails(mediaHanlderId); } std::vector<std::string> getCallMediaHandlerStatus(const std::string& callId) { return libjami::getCallMediaHandlerStatus(callId); } std::map<std::string, std::string> getChatHandlerDetails(const std::string& chatHanlderId) { return libjami::getChatHandlerDetails(chatHanlderId); } std::vector<std::string> getChatHandlerStatus(const std::string& accountId, const std::string& peerId) { return libjami::getChatHandlerStatus(accountId, peerId); } bool getPluginsEnabled() { return libjami::getPluginsEnabled(); } void setPluginsEnabled(const bool& state) { libjami::setPluginsEnabled(state); } void sendWebViewMessage(const std::string& pluginId, const std::string& webViewId, const std::string& messageId, const std::string& payload) { libjami::sendWebViewAttach(pluginId, webViewId, messageId, payload); } std::string sendWebViewAttach(const std::string& pluginId, const std::string& accountId, const std::string& webViewId, const std::string& action) { return libjami::sendWebViewAttach(pluginId, accountId, webViewId, action); } void sendWebViewDetach(const std::string& pluginId, const std::string& webViewId) { libjami::sendWebViewDetach(pluginId, webViewId); } private: void registerSignalHandlers() { using namespace std::placeholders; using libjami::exportable_serialized_callback; using SharedCallback = std::shared_ptr<libjami::CallbackWrapperBase>; const std::map<std::string, SharedCallback> pluginEvHandlers = { exportable_serialized_callback<libjami::PluginSignal::WebViewMessageReceived>( std::bind(&DBusPluginManagerInterface::emitWebViewMessageReceived, this, _1, _2, _3, _4)), }; libjami::registerSignalHandlers(pluginEvHandlers); } };
6,380
C++
.h
190
25.952632
114
0.650966
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,851
dbusinstance.hpp
savoirfairelinux_jami-daemon/bin/dbus/dbusinstance.hpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "dbusinstance.adaptor.h" #include <sdbus-c++/IConnection.h> #include <cstdint> #include <memory> extern bool persistent; extern std::unique_ptr<sdbus::IConnection> connection; class DBusInstance : public sdbus::AdaptorInterfaces<cx::ring::Ring::Instance_adaptor> { public: DBusInstance(sdbus::IConnection& connection) : AdaptorInterfaces(connection, "/cx/ring/Ring/Instance") { registerAdaptor(); } ~DBusInstance() { unregisterAdaptor(); } void Register(const int32_t& /*pid*/, const std::string& /*name*/) { ++count_; } void Unregister(const int32_t& /*pid*/) { --count_; if (!persistent && count_ <= 0) { connection->leaveEventLoop(); } } private: int_least16_t count_ {0}; };
1,554
C++
.h
51
26.509804
86
0.687625
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,852
dbusconfigurationmanager.hpp
savoirfairelinux_jami-daemon/bin/dbus/dbusconfigurationmanager.hpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "dbusconfigurationmanager.adaptor.h" #include <configurationmanager_interface.h> #include <datatransfer_interface.h> #include <conversation_interface.h> class DBusConfigurationManager : public sdbus::AdaptorInterfaces<cx::ring::Ring::ConfigurationManager_adaptor> { public: using DBusSwarmMessage = sdbus::Struct<std::string, std::string, std::string, std::map<std::string, std::string>, std::vector<std::map<std::string, std::string>>, std::vector<std::map<std::string, std::string>>, std::map<std::string, int32_t>>; DBusConfigurationManager(sdbus::IConnection& connection) : AdaptorInterfaces(connection, "/cx/ring/Ring/ConfigurationManager") { registerAdaptor(); registerSignalHandlers(); } ~DBusConfigurationManager() { unregisterAdaptor(); } auto getAccountDetails(const std::string& accountID) -> decltype(libjami::getAccountDetails(accountID)) { return libjami::getAccountDetails(accountID); } auto getVolatileAccountDetails(const std::string& accountID) -> decltype(libjami::getVolatileAccountDetails(accountID)) { return libjami::getVolatileAccountDetails(accountID); } void setAccountDetails(const std::string& accountID, const std::map<std::string, std::string>& details) { libjami::setAccountDetails(accountID, details); } void setAccountActive(const std::string& accountID, const bool& active) { libjami::setAccountActive(accountID, active); } auto getAccountTemplate(const std::string& accountType) -> decltype(libjami::getAccountTemplate(accountType)) { return libjami::getAccountTemplate(accountType); } auto addAccount(const std::map<std::string, std::string>& details) -> decltype(libjami::addAccount(details)) { return libjami::addAccount(details); } auto monitor(const bool& continuous) -> decltype(libjami::monitor(continuous)) { return libjami::monitor(continuous); } auto exportOnRing(const std::string& accountID, const std::string& password) -> decltype(libjami::exportOnRing(accountID, password)) { return libjami::exportOnRing(accountID, password); } auto exportToFile(const std::string& accountID, const std::string& destinationPath, const std::string& scheme, const std::string& password) -> decltype(libjami::exportToFile(accountID, destinationPath, scheme, password)) { return libjami::exportToFile(accountID, destinationPath, scheme, password); } auto revokeDevice(const std::string& accountID, const std::string& device, const std::string& scheme, const std::string& password) -> decltype(libjami::revokeDevice(accountID, device, scheme, password)) { return libjami::revokeDevice(accountID, device, scheme, password); } auto getKnownRingDevices(const std::string& accountID) -> decltype(libjami::getKnownRingDevices(accountID)) { return libjami::getKnownRingDevices(accountID); } auto changeAccountPassword(const std::string& accountID, const std::string& password_old, const std::string& password_new) -> decltype(libjami::changeAccountPassword(accountID, password_old, password_new)) { return libjami::changeAccountPassword(accountID, password_old, password_new); } auto lookupName(const std::string& account, const std::string& nameserver, const std::string& name) -> decltype(libjami::lookupName(account, nameserver, name)) { return libjami::lookupName(account, nameserver, name); } auto lookupAddress(const std::string& account, const std::string& nameserver, const std::string& address) -> decltype(libjami::lookupAddress(account, nameserver, address)) { return libjami::lookupAddress(account, nameserver, address); } auto registerName(const std::string& account, const std::string& name, const std::string& scheme, const std::string& password) -> decltype(libjami::registerName(account, name, scheme, password)) { return libjami::registerName(account, name, scheme, password); } auto searchUser(const std::string& account, const std::string& query) -> decltype(libjami::searchUser(account, query)) { return libjami::searchUser(account, query); } void removeAccount(const std::string& accountID) { libjami::removeAccount(accountID); } auto getAccountList() -> decltype(libjami::getAccountList()) { return libjami::getAccountList(); } void sendRegister(const std::string& accountID, const bool& enable) { libjami::sendRegister(accountID, enable); } void registerAllAccounts(void) { libjami::registerAllAccounts(); } auto sendTextMessage(const std::string& accountID, const std::string& to, const std::map<std::string, std::string>& payloads, const int32_t& flags) -> decltype(libjami::sendAccountTextMessage(accountID, to, payloads, flags)) { return libjami::sendAccountTextMessage(accountID, to, payloads, flags); } std::vector<sdbus::Struct<std::string, std::map<std::string, std::string>, uint64_t>> getLastMessages(const std::string& accountID, const uint64_t& base_timestamp) { auto messages = libjami::getLastMessages(accountID, base_timestamp); std::vector<sdbus::Struct<std::string, std::map<std::string, std::string>, uint64_t>> result; for (const auto& message : messages) { sdbus::Struct<std::string, std::map<std::string, std::string>, uint64_t> m( message.from, message.payloads, message.received ); result.emplace_back(m); } return result; } std::map<std::string, std::string> getNearbyPeers(const std::string& accountID) { return libjami::getNearbyPeers(accountID); } void updateProfile(const std::string& accountID,const std::string& displayName, const std::string& avatar, const uint64_t& flag) { libjami::updateProfile(accountID, displayName, avatar, flag); } auto getMessageStatus(const uint64_t& id) -> decltype(libjami::getMessageStatus(id)) { return libjami::getMessageStatus(id); } auto getMessageStatus(const std::string& accountID, const uint64_t& id) -> decltype(libjami::getMessageStatus(accountID, id)) { return libjami::getMessageStatus(accountID, id); } bool cancelMessage(const std::string& accountID, const uint64_t& id) { return libjami::cancelMessage(accountID, id); } void setIsComposing(const std::string& accountID, const std::string& conversationUri, const bool& isWriting) { libjami::setIsComposing(accountID, conversationUri, isWriting); } bool setMessageDisplayed(const std::string& accountID, const std::string& conversationUri, const std::string& messageId, const int32_t& status) { return libjami::setMessageDisplayed(accountID, conversationUri, messageId, status); } auto getCodecList() -> decltype(libjami::getCodecList()) { return libjami::getCodecList(); } auto getSupportedTlsMethod() -> decltype(libjami::getSupportedTlsMethod()) { return libjami::getSupportedTlsMethod(); } auto getSupportedCiphers(const std::string& accountID) -> decltype(libjami::getSupportedCiphers(accountID)) { return libjami::getSupportedCiphers(accountID); } auto getCodecDetails(const std::string& accountID, const unsigned& codecId) -> decltype(libjami::getCodecDetails(accountID, codecId)) { return libjami::getCodecDetails(accountID, codecId); } auto setCodecDetails(const std::string& accountID, const unsigned& codecId, const std::map<std::string, std::string>& details) -> decltype(libjami::setCodecDetails(accountID, codecId, details)) { return libjami::setCodecDetails(accountID, codecId, details); } auto getActiveCodecList(const std::string& accountID) -> decltype(libjami::getActiveCodecList(accountID)) { return libjami::getActiveCodecList(accountID); } void setActiveCodecList(const std::string& accountID, const std::vector<unsigned>& list) { libjami::setActiveCodecList(accountID, list); } auto getAudioPluginList() -> decltype(libjami::getAudioPluginList()) { return libjami::getAudioPluginList(); } void setAudioPlugin(const std::string& audioPlugin) { libjami::setAudioPlugin(audioPlugin); } auto getAudioOutputDeviceList() -> decltype(libjami::getAudioOutputDeviceList()) { return libjami::getAudioOutputDeviceList(); } void setAudioOutputDevice(const int32_t& index) { libjami::setAudioOutputDevice(index); } void setAudioInputDevice(const int32_t& index) { libjami::setAudioInputDevice(index); } void setAudioRingtoneDevice(const int32_t& index) { libjami::setAudioRingtoneDevice(index); } auto getAudioInputDeviceList() -> decltype(libjami::getAudioInputDeviceList()) { return libjami::getAudioInputDeviceList(); } auto getCurrentAudioDevicesIndex() -> decltype(libjami::getCurrentAudioDevicesIndex()) { return libjami::getCurrentAudioDevicesIndex(); } auto getAudioInputDeviceIndex(const std::string& name) -> decltype(libjami::getAudioInputDeviceIndex(name)) { return libjami::getAudioInputDeviceIndex(name); } auto getAudioOutputDeviceIndex(const std::string& name) -> decltype(libjami::getAudioOutputDeviceIndex(name)) { return libjami::getAudioOutputDeviceIndex(name); } auto getCurrentAudioOutputPlugin() -> decltype(libjami::getCurrentAudioOutputPlugin()) { return libjami::getCurrentAudioOutputPlugin(); } auto getNoiseSuppressState() -> decltype(libjami::getNoiseSuppressState()) { return libjami::getNoiseSuppressState(); } void setNoiseSuppressState(const std::string& state) { libjami::setNoiseSuppressState(state); } auto isAgcEnabled() -> decltype(libjami::isAgcEnabled()) { return libjami::isAgcEnabled(); } void setAgcState(const bool& enabled) { libjami::setAgcState(enabled); } void muteDtmf(const bool& mute) { libjami::muteDtmf(mute); } auto isDtmfMuted() -> decltype(libjami::isDtmfMuted()) { return libjami::isDtmfMuted(); } auto isCaptureMuted() -> decltype(libjami::isCaptureMuted()) { return libjami::isCaptureMuted(); } void muteCapture(const bool& mute) { libjami::muteCapture(mute); } auto isPlaybackMuted() -> decltype(libjami::isPlaybackMuted()) { return libjami::isPlaybackMuted(); } void mutePlayback(const bool& mute) { libjami::mutePlayback(mute); } auto isRingtoneMuted() -> decltype(libjami::isRingtoneMuted()) { return libjami::isRingtoneMuted(); } void muteRingtone(const bool& mute) { libjami::muteRingtone(mute); } auto getAudioManager() -> decltype(libjami::getAudioManager()) { return libjami::getAudioManager(); } auto setAudioManager(const std::string& api) -> decltype(libjami::setAudioManager(api)) { return libjami::setAudioManager(api); } auto getSupportedAudioManagers() -> decltype(libjami::getSupportedAudioManagers()) { return libjami::getSupportedAudioManagers(); } auto getRecordPath() -> decltype(libjami::getRecordPath()) { return libjami::getRecordPath(); } void setRecordPath(const std::string& recPath) { libjami::setRecordPath(recPath); } auto getIsAlwaysRecording() -> decltype(libjami::getIsAlwaysRecording()) { return libjami::getIsAlwaysRecording(); } void setIsAlwaysRecording(const bool& rec) { libjami::setIsAlwaysRecording(rec); } auto getRecordPreview() -> decltype(libjami::getRecordPreview()) { return libjami::getRecordPreview(); } void setRecordPreview(const bool& rec) { libjami::setRecordPreview(rec); } auto getRecordQuality() -> decltype(libjami::getRecordQuality()) { return libjami::getRecordQuality(); } void setRecordQuality(const int32_t& quality) { libjami::setRecordQuality(quality); } void setHistoryLimit(const int32_t& days) { libjami::setHistoryLimit(days); } auto getHistoryLimit() -> decltype(libjami::getHistoryLimit()) { return libjami::getHistoryLimit(); } void setRingingTimeout(const int32_t& timeout) { libjami::setRingingTimeout(timeout); } auto getRingingTimeout() -> decltype(libjami::getRingingTimeout()) { return libjami::getRingingTimeout(); } void setAccountsOrder(const std::string& order) { libjami::setAccountsOrder(order); } auto validateCertificate(const std::string& accountId, const std::string& certificate) -> decltype(libjami::validateCertificate(accountId, certificate)) { return libjami::validateCertificate(accountId, certificate); } auto validateCertificatePath(const std::string& accountId, const std::string& certificate, const std::string& privateKey, const std::string& privateKeyPass, const std::string& caList) -> decltype(libjami::validateCertificatePath( accountId, certificate, privateKey, privateKeyPass, caList)) { return libjami::validateCertificatePath(accountId, certificate, privateKey, privateKeyPass, caList); } auto getCertificateDetails(const std::string& accountId, const std::string& certificate) -> decltype(libjami::getCertificateDetails(accountId, certificate)) { return libjami::getCertificateDetails(accountId, certificate); } auto getCertificateDetailsPath(const std::string& accountId, const std::string& certificate, const std::string& privateKey, const std::string& privateKeyPass) -> decltype(libjami::getCertificateDetailsPath( accountId, certificate, privateKey, privateKeyPass)) { return libjami::getCertificateDetailsPath(accountId, certificate, privateKey, privateKeyPass); } auto getPinnedCertificates(const std::string& accountId) -> decltype(libjami::getPinnedCertificates(accountId)) { return libjami::getPinnedCertificates(accountId); } auto pinCertificate(const std::string& accountId, const std::vector<uint8_t>& certificate, const bool& local) -> decltype(libjami::pinCertificate(accountId, certificate, local)) { return libjami::pinCertificate(accountId, certificate, local); } void pinCertificatePath(const std::string& accountId, const std::string& certPath) { libjami::pinCertificatePath(accountId, certPath); } auto unpinCertificate(const std::string& accountId, const std::string& certId) -> decltype(libjami::unpinCertificate(accountId, certId)) { return libjami::unpinCertificate(accountId, certId); } auto unpinCertificatePath(const std::string& accountId, const std::string& p) -> decltype(libjami::unpinCertificatePath(accountId, p)) { return libjami::unpinCertificatePath(accountId, p); } auto pinRemoteCertificate(const std::string& accountId, const std::string& certId) -> decltype(libjami::pinRemoteCertificate(accountId, certId)) { return libjami::pinRemoteCertificate(accountId, certId); } auto setCertificateStatus(const std::string& accountId, const std::string& certId, const std::string& status) -> decltype(libjami::setCertificateStatus(accountId, certId, status)) { return libjami::setCertificateStatus(accountId, certId, status); } auto getCertificatesByStatus(const std::string& accountId, const std::string& status) -> decltype(libjami::getCertificatesByStatus(accountId, status)) { return libjami::getCertificatesByStatus(accountId, status); } auto getTrustRequests(const std::string& accountId) -> decltype(libjami::getTrustRequests(accountId)) { return libjami::getTrustRequests(accountId); } auto acceptTrustRequest(const std::string& accountId, const std::string& from) -> decltype(libjami::acceptTrustRequest(accountId, from)) { return libjami::acceptTrustRequest(accountId, from); } auto discardTrustRequest(const std::string& accountId, const std::string& from) -> decltype(libjami::discardTrustRequest(accountId, from)) { return libjami::discardTrustRequest(accountId, from); } void sendTrustRequest(const std::string& accountId, const std::string& to, const std::vector<uint8_t>& payload) { libjami::sendTrustRequest(accountId, to, payload); } void addContact(const std::string& accountId, const std::string& uri) { libjami::addContact(accountId, uri); } void removeContact(const std::string& accountId, const std::string& uri, const bool& ban) { libjami::removeContact(accountId, uri, ban); } auto getContactDetails(const std::string& accountId, const std::string& uri) -> decltype(libjami::getContactDetails(accountId, uri)) { return libjami::getContactDetails(accountId, uri); } auto getConnectionList(const std::string& accountId, const std::string& conversationId) -> decltype(libjami::getConnectionList(accountId, conversationId)) { return libjami::getConnectionList(accountId,conversationId); } auto getChannelList(const std::string& accountId, const std::string& connectionId) -> decltype(libjami::getChannelList(accountId, connectionId)) { return libjami::getChannelList(accountId,connectionId); } auto getContacts(const std::string& accountId) -> decltype(libjami::getContacts(accountId)) { return libjami::getContacts(accountId); } auto getCredentials(const std::string& accountID) -> decltype(libjami::getCredentials(accountID)) { return libjami::getCredentials(accountID); } void setCredentials( const std::string& accountID, const std::vector<std::map<std::string, std::string>>& details) { libjami::setCredentials(accountID, details); } auto getAddrFromInterfaceName(const std::string& interface) -> decltype(libjami::getAddrFromInterfaceName(interface)) { return libjami::getAddrFromInterfaceName(interface); } auto getAllIpInterface() -> decltype(libjami::getAllIpInterface()) { return libjami::getAllIpInterface(); } auto getAllIpInterfaceByName() -> decltype(libjami::getAllIpInterfaceByName()) { return libjami::getAllIpInterfaceByName(); } void setVolume(const std::string& device, const double& value) { libjami::setVolume(device, value); } auto getVolume(const std::string& device) -> decltype(libjami::getVolume(device)) { return libjami::getVolume(device); } void connectivityChanged() { libjami::connectivityChanged(); } void sendFile(const std::string& accountId, const std::string& conversationId, const std::string& path, const std::string& displayName, const std::string& replyTo) { libjami::sendFile(accountId, conversationId, path, displayName, replyTo); } std::tuple<uint32_t, std::string, int64_t, int64_t> fileTransferInfo(const std::string& accountId, const std::string& to, const std::string& fileId) { uint32_t error; std::string path; int64_t total; int64_t progress; error = (uint32_t) libjami::fileTransferInfo(accountId, to, fileId, path, total, progress); return {error, path, total, progress}; } bool downloadFile(const std::string& accountId, const std::string& conversationUri, const std::string& interactionId, const std::string& fileId, const std::string& path) { return libjami::downloadFile(accountId, conversationUri, interactionId, fileId, path); } uint32_t cancelDataTransfer(const std::string& accountId, const std::string& conversationId, const std::string& fileId) { return uint32_t(libjami::cancelDataTransfer(accountId, conversationId, fileId)); } std::string startConversation(const std::string& accountId) { return libjami::startConversation(accountId); } void acceptConversationRequest(const std::string& accountId, const std::string& conversationId) { libjami::acceptConversationRequest(accountId, conversationId); } void declineConversationRequest(const std::string& accountId, const std::string& conversationId) { libjami::declineConversationRequest(accountId, conversationId); } bool removeConversation(const std::string& accountId, const std::string& conversationId) { return libjami::removeConversation(accountId, conversationId); } std::vector<std::string> getConversations(const std::string& accountId) { return libjami::getConversations(accountId); } std::vector<std::map<std::string, std::string>> getActiveCalls(const std::string& accountId, const std::string& conversationId) { return libjami::getActiveCalls(accountId, conversationId); } std::vector<std::map<std::string, std::string>> getConversationRequests(const std::string& accountId) { return libjami::getConversationRequests(accountId); } void updateConversationInfos(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& infos) { libjami::updateConversationInfos(accountId, conversationId, infos); } std::map<std::string, std::string> conversationInfos(const std::string& accountId, const std::string& conversationId) { return libjami::conversationInfos(accountId, conversationId); } void setConversationPreferences(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& infos) { libjami::setConversationPreferences(accountId, conversationId, infos); } std::map<std::string, std::string> getConversationPreferences(const std::string& accountId, const std::string& conversationId) { return libjami::getConversationPreferences(accountId, conversationId); } void addConversationMember(const std::string& accountId, const std::string& conversationId, const std::string& contactUri) { libjami::addConversationMember(accountId, conversationId, contactUri); } void removeConversationMember(const std::string& accountId, const std::string& conversationId, const std::string& contactUri) { libjami::removeConversationMember(accountId, conversationId, contactUri); } std::vector<std::map<std::string, std::string>> getConversationMembers(const std::string& accountId, const std::string& conversationId) { return libjami::getConversationMembers(accountId, conversationId); } void sendMessage(const std::string& accountId, const std::string& conversationId, const std::string& message, const std::string& replyTo, const int32_t& flag) { libjami::sendMessage(accountId, conversationId, message, replyTo, flag); } uint32_t loadConversationMessages(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, const uint32_t& n) { return libjami::loadConversationMessages(accountId, conversationId, fromMessage, n); } uint32_t loadConversation(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, const uint32_t& n) { return libjami::loadConversation(accountId, conversationId, fromMessage, n); } uint32_t loadConversationUntil(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, const std::string& to) { return libjami::loadConversationUntil(accountId, conversationId, fromMessage, to); } uint32_t loadSwarmUntil(const std::string& accountId, const std::string& conversationId, const std::string& fromMessage, const std::string& toMessage) { return libjami::loadSwarmUntil(accountId, conversationId, fromMessage, toMessage); } uint32_t countInteractions(const std::string& accountId, const std::string& conversationId, const std::string& toId, const std::string& fromId, const std::string& authorUri) { return libjami::countInteractions(accountId, conversationId, toId, fromId, authorUri); } void clearCache(const std::string& accountId, const std::string& conversationId) { return libjami::clearCache(accountId, conversationId); } uint32_t searchConversation(const std::string& accountId, const std::string& conversationId, const std::string& author, const std::string& lastId, const std::string& regexSearch, const std::string& type, const int64_t& after, const int64_t& before, const uint32_t& maxResult, const int32_t& flag) { return libjami::searchConversation(accountId, conversationId, author, lastId, regexSearch, type, after, before, maxResult, flag); } bool isAudioMeterActive(const std::string& id) { return libjami::isAudioMeterActive(id); } void setAudioMeterState(const std::string& id, const bool& state) { return libjami::setAudioMeterState(id, state); } void setDefaultModerator(const std::string& accountID, const std::string& peerURI, const bool& state) { libjami::setDefaultModerator(accountID, peerURI, state); } auto getDefaultModerators(const std::string& accountID) -> decltype(libjami::getDefaultModerators(accountID)) { return libjami::getDefaultModerators(accountID); } void enableLocalModerators(const std::string& accountID, const bool& isModEnabled) { return libjami::enableLocalModerators(accountID, isModEnabled); } bool isLocalModeratorsEnabled(const std::string& accountID) { return libjami::isLocalModeratorsEnabled(accountID); } void setAllModerators(const std::string& accountID, const bool& allModerators) { return libjami::setAllModerators(accountID, allModerators); } bool isAllModerators(const std::string& accountID) { return libjami::isAllModerators(accountID); } private: void registerSignalHandlers() { using namespace std::placeholders; using libjami::exportable_serialized_callback; using libjami::ConfigurationSignal; using libjami::AudioSignal; using libjami::DataTransferSignal; using libjami::ConversationSignal; using SharedCallback = std::shared_ptr<libjami::CallbackWrapperBase>; // Configuration event handlers const std::map<std::string, SharedCallback> configEvHandlers = { exportable_serialized_callback<ConfigurationSignal::VolumeChanged>( std::bind(&DBusConfigurationManager::emitVolumeChanged, this, _1, _2)), exportable_serialized_callback<ConfigurationSignal::AccountsChanged>( std::bind(&DBusConfigurationManager::emitAccountsChanged, this)), exportable_serialized_callback<ConfigurationSignal::AccountDetailsChanged>( std::bind(&DBusConfigurationManager::emitAccountDetailsChanged, this, _1, _2)), exportable_serialized_callback<ConfigurationSignal::StunStatusFailed>( std::bind(&DBusConfigurationManager::emitStunStatusFailure, this, _1)), exportable_serialized_callback<ConfigurationSignal::RegistrationStateChanged>( std::bind(&DBusConfigurationManager::emitRegistrationStateChanged, this, _1, _2, _3, _4)), exportable_serialized_callback<ConfigurationSignal::VolatileDetailsChanged>( std::bind(&DBusConfigurationManager::emitVolatileAccountDetailsChanged, this, _1, _2)), exportable_serialized_callback<ConfigurationSignal::Error>( std::bind(&DBusConfigurationManager::emitErrorAlert, this, _1)), exportable_serialized_callback<ConfigurationSignal::IncomingAccountMessage>( std::bind(&DBusConfigurationManager::emitIncomingAccountMessage, this, _1, _2, _3, _4)), exportable_serialized_callback<ConfigurationSignal::AccountMessageStatusChanged>( std::bind(&DBusConfigurationManager::emitAccountMessageStatusChanged, this, _1, _2, _3, _4, _5)), exportable_serialized_callback<ConfigurationSignal::ProfileReceived>( std::bind(&DBusConfigurationManager::emitProfileReceived, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::ActiveCallsChanged>( std::bind(&DBusConfigurationManager::emitActiveCallsChanged, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::ComposingStatusChanged>( std::bind(&DBusConfigurationManager::emitComposingStatusChanged, this, _1, _2, _3, _4)), exportable_serialized_callback<ConfigurationSignal::IncomingTrustRequest>( std::bind(&DBusConfigurationManager::emitIncomingTrustRequest, this, _1, _2, _3, _4, _5)), exportable_serialized_callback<ConfigurationSignal::ContactAdded>( std::bind(&DBusConfigurationManager::emitContactAdded, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::ContactRemoved>( std::bind(&DBusConfigurationManager::emitContactRemoved, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::ExportOnRingEnded>( std::bind(&DBusConfigurationManager::emitExportOnRingEnded, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::KnownDevicesChanged>( std::bind(&DBusConfigurationManager::emitKnownDevicesChanged, this, _1, _2)), exportable_serialized_callback<ConfigurationSignal::NameRegistrationEnded>( std::bind(&DBusConfigurationManager::emitNameRegistrationEnded, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::UserSearchEnded>( std::bind(&DBusConfigurationManager::emitUserSearchEnded, this, _1, _2, _3, _4)), exportable_serialized_callback<ConfigurationSignal::RegisteredNameFound>( std::bind(&DBusConfigurationManager::emitRegisteredNameFound, this, _1, _2, _3, _4)), exportable_serialized_callback<ConfigurationSignal::DeviceRevocationEnded>( std::bind(&DBusConfigurationManager::emitDeviceRevocationEnded, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::AccountProfileReceived>( std::bind(&DBusConfigurationManager::emitAccountProfileReceived, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::CertificatePinned>( std::bind(&DBusConfigurationManager::emitCertificatePinned, this, _1)), exportable_serialized_callback<ConfigurationSignal::CertificatePathPinned>( std::bind(&DBusConfigurationManager::emitCertificatePathPinned, this, _1, _2)), exportable_serialized_callback<ConfigurationSignal::CertificateExpired>( std::bind(&DBusConfigurationManager::emitCertificateExpired, this, _1)), exportable_serialized_callback<ConfigurationSignal::CertificateStateChanged>( std::bind(&DBusConfigurationManager::emitCertificateStateChanged, this, _1, _2, _3)), exportable_serialized_callback<ConfigurationSignal::MediaParametersChanged>( std::bind(&DBusConfigurationManager::emitMediaParametersChanged, this, _1)), exportable_serialized_callback<ConfigurationSignal::MigrationEnded>( std::bind(&DBusConfigurationManager::emitMigrationEnded, this, _1, _2)), exportable_serialized_callback<ConfigurationSignal::HardwareDecodingChanged>( std::bind(&DBusConfigurationManager::emitHardwareDecodingChanged, this, _1)), exportable_serialized_callback<ConfigurationSignal::HardwareEncodingChanged>( std::bind(&DBusConfigurationManager::emitHardwareEncodingChanged, this, _1)), exportable_serialized_callback<ConfigurationSignal::MessageSend>( std::bind(&DBusConfigurationManager::emitMessageSend, this, _1)), }; // Audio event handlers const std::map<std::string, SharedCallback> audioEvHandlers = { exportable_serialized_callback<AudioSignal::DeviceEvent>( std::bind(&DBusConfigurationManager::emitAudioDeviceEvent, this)), exportable_serialized_callback<AudioSignal::AudioMeter>( std::bind(&DBusConfigurationManager::emitAudioMeter, this, _1, _2)), }; const std::map<std::string, SharedCallback> dataXferEvHandlers = { exportable_serialized_callback<DataTransferSignal::DataTransferEvent>( std::bind(&DBusConfigurationManager::emitDataTransferEvent, this, _1, _2, _3, _4, _5)), }; const std::map<std::string, SharedCallback> convEvHandlers = { exportable_serialized_callback<ConversationSignal::ConversationLoaded>( std::bind(&DBusConfigurationManager::emitConversationLoaded, this, _1, _2, _3, _4)), exportable_serialized_callback<ConversationSignal::SwarmLoaded>([this](const uint32_t& id, const std::string& account_id, const std::string& conversation_id, const std::vector<libjami::SwarmMessage>& messages) { std::vector<DBusSwarmMessage> msgList; for (const auto& message: messages) { DBusSwarmMessage msg {message.id, message.type, message.linearizedParent, message.body, message.reactions, message.editions, message.status}; msgList.push_back(msg); } DBusConfigurationManager::emitSwarmLoaded(id, account_id, conversation_id, msgList); }), exportable_serialized_callback<ConversationSignal::MessagesFound>( std::bind(&DBusConfigurationManager::emitMessagesFound, this, _1, _2, _3, _4)), exportable_serialized_callback<ConversationSignal::MessageReceived>( std::bind(&DBusConfigurationManager::emitMessageReceived, this, _1, _2, _3)), exportable_serialized_callback<ConversationSignal::SwarmMessageReceived>([this](const std::string& account_id, const std::string& conversation_id, const libjami::SwarmMessage& message) { DBusSwarmMessage msg {message.id, message.type, message.linearizedParent, message.body, message.reactions, message.editions, message.status}; DBusConfigurationManager::emitSwarmMessageReceived(account_id, conversation_id, msg); }), exportable_serialized_callback<ConversationSignal::SwarmMessageUpdated>([this](const std::string& account_id, const std::string& conversation_id, const libjami::SwarmMessage& message) { DBusSwarmMessage msg {message.id, message.type, message.linearizedParent, message.body, message.reactions, message.editions, message.status}; DBusConfigurationManager::emitSwarmMessageUpdated(account_id, conversation_id, msg); }), exportable_serialized_callback<ConversationSignal::ReactionAdded>( std::bind(&DBusConfigurationManager::emitReactionAdded, this, _1, _2, _3, _4)), exportable_serialized_callback<ConversationSignal::ReactionRemoved>( std::bind(&DBusConfigurationManager::emitReactionRemoved, this, _1, _2, _3, _4)), exportable_serialized_callback<ConversationSignal::ConversationProfileUpdated>( std::bind(&DBusConfigurationManager::emitConversationProfileUpdated, this, _1, _2, _3)), exportable_serialized_callback<ConversationSignal::ConversationRequestReceived>( std::bind(&DBusConfigurationManager::emitConversationRequestReceived, this, _1, _2, _3)), exportable_serialized_callback<ConversationSignal::ConversationRequestDeclined>( std::bind(&DBusConfigurationManager::emitConversationRequestDeclined, this, _1, _2)), exportable_serialized_callback<ConversationSignal::ConversationReady>( std::bind(&DBusConfigurationManager::emitConversationReady, this, _1, _2)), exportable_serialized_callback<ConversationSignal::ConversationRemoved>( std::bind(&DBusConfigurationManager::emitConversationRemoved, this, _1, _2)), exportable_serialized_callback<ConversationSignal::ConversationMemberEvent>( std::bind(&DBusConfigurationManager::emitConversationMemberEvent, this, _1, _2, _3, _4)), exportable_serialized_callback<ConversationSignal::OnConversationError>( std::bind(&DBusConfigurationManager::emitOnConversationError, this, _1, _2, _3, _4)), exportable_serialized_callback<ConversationSignal::ConversationPreferencesUpdated>( std::bind(&DBusConfigurationManager::emitConversationPreferencesUpdated, this, _1, _2, _3)), }; libjami::registerSignalHandlers(configEvHandlers); libjami::registerSignalHandlers(audioEvHandlers); libjami::registerSignalHandlers(dataXferEvHandlers); libjami::registerSignalHandlers(convEvHandlers); } };
42,467
C++
.h
1,052
30.963878
248
0.646553
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,853
dbuspresencemanager.hpp
savoirfairelinux_jami-daemon/bin/dbus/dbuspresencemanager.hpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "dbuspresencemanager.adaptor.h" #include <presencemanager_interface.h> class DBusPresenceManager : public sdbus::AdaptorInterfaces<cx::ring::Ring::PresenceManager_adaptor> { public: DBusPresenceManager(sdbus::IConnection& connection) : AdaptorInterfaces(connection, "/cx/ring/Ring/PresenceManager") { registerAdaptor(); registerSignalHandlers(); } ~DBusPresenceManager() { unregisterAdaptor(); } void publish(const std::string& accountID, const bool& status, const std::string& note) { libjami::publish(accountID, status, note); } void answerServerRequest(const std::string& uri, const bool& flag) { libjami::answerServerRequest(uri, flag); } void subscribeBuddy(const std::string& accountID, const std::string& uri, const bool& flag) { libjami::subscribeBuddy(accountID, uri, flag); } auto getSubscriptions(const std::string& accountID) -> decltype(libjami::getSubscriptions(accountID)) { return libjami::getSubscriptions(accountID); } void setSubscriptions(const std::string& accountID, const std::vector<std::string>& uris) { libjami::setSubscriptions(accountID, uris); } private: void registerSignalHandlers() { using namespace std::placeholders; using libjami::exportable_serialized_callback; using libjami::PresenceSignal; using SharedCallback = std::shared_ptr<libjami::CallbackWrapperBase>; const std::map<std::string, SharedCallback> presEvHandlers = { exportable_serialized_callback<PresenceSignal::NewServerSubscriptionRequest>( std::bind(&DBusPresenceManager::emitNewServerSubscriptionRequest, this, _1)), exportable_serialized_callback<PresenceSignal::ServerError>( std::bind(&DBusPresenceManager::emitServerError, this, _1, _2, _3)), exportable_serialized_callback<PresenceSignal::NewBuddyNotification>( std::bind(&DBusPresenceManager::emitNewBuddyNotification, this, _1, _2, _3, _4)), exportable_serialized_callback<PresenceSignal::NearbyPeerNotification>( std::bind(&DBusPresenceManager::emitNearbyPeerNotification, this, _1, _2, _3, _4)), exportable_serialized_callback<PresenceSignal::SubscriptionStateChanged>( std::bind(&DBusPresenceManager::emitSubscriptionStateChanged, this, _1, _2, _3)), }; libjami::registerSignalHandlers(presEvHandlers); } };
3,309
C++
.h
80
35.1625
100
0.703358
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,854
dbusvideomanager.hpp
savoirfairelinux_jami-daemon/bin/dbus/dbusvideomanager.hpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "dbusvideomanager.adaptor.h" #include <videomanager_interface.h> class DBusVideoManager : public sdbus::AdaptorInterfaces<cx::ring::Ring::VideoManager_adaptor> { public: DBusVideoManager(sdbus::IConnection& connection) : AdaptorInterfaces(connection, "/cx/ring/Ring/VideoManager") { registerAdaptor(); registerSignalHandlers(); } ~DBusVideoManager() { unregisterAdaptor(); } auto getDeviceList() -> decltype(libjami::getDeviceList()) { return libjami::getDeviceList(); } auto getCapabilities(const std::string& deviceId) -> decltype(libjami::getCapabilities(deviceId)) { return libjami::getCapabilities(deviceId); } auto getSettings(const std::string& deviceId) -> decltype(libjami::getSettings(deviceId)) { return libjami::getSettings(deviceId); } void applySettings(const std::string& deviceId, const std::map<std::string, std::string>& settings) { libjami::applySettings(deviceId, settings); } void setDefaultDevice(const std::string& deviceId) { libjami::setDefaultDevice(deviceId); } auto getDefaultDevice() -> decltype(libjami::getDefaultDevice()) { return libjami::getDefaultDevice(); } void startAudioDevice() { libjami::startAudioDevice(); } void stopAudioDevice() { libjami::stopAudioDevice(); } std::string openVideoInput(const std::string& inputUri) { return libjami::openVideoInput(inputUri); } bool closeVideoInput(const std::string& inputId) { return libjami::closeVideoInput(inputId); } auto getDecodingAccelerated() -> decltype(libjami::getDecodingAccelerated()) { return libjami::getDecodingAccelerated(); } void setDecodingAccelerated(const bool& state) { libjami::setDecodingAccelerated(state); } auto getEncodingAccelerated() -> decltype(libjami::getEncodingAccelerated()) { return libjami::getEncodingAccelerated(); } void setEncodingAccelerated(const bool& state) { libjami::setEncodingAccelerated(state); } void setDeviceOrientation(const std::string& deviceId, const int& angle) { libjami::setDeviceOrientation(deviceId, angle); } void startShmSink(const std::string& sinkId, const bool& value) { libjami::startShmSink(sinkId, value); } std::map<std::string, std::string> getRenderer(const std::string& callId) { return libjami::getRenderer(callId); } std::string startLocalMediaRecorder(const std::string& videoInputId, const std::string& filepath) { return libjami::startLocalMediaRecorder(videoInputId, filepath); } void stopLocalRecorder(const std::string& filepath) { libjami::stopLocalRecorder(filepath); } std::string createMediaPlayer(const std::string& path) { return libjami::createMediaPlayer(path); } bool pausePlayer(const std::string& id, const bool& pause) { return libjami::pausePlayer(id, pause); } bool closeMediaPlayer(const std::string& id) { return libjami::closeMediaPlayer(id); } bool mutePlayerAudio(const std::string& id, const bool& mute) { return libjami::mutePlayerAudio(id, mute); } bool playerSeekToTime(const std::string& id, const int& time) { return libjami::playerSeekToTime(id, time); } int64_t getPlayerPosition(const std::string& id) { return libjami::getPlayerPosition(id); } int64_t getPlayerDuration(const std::string& id) { return libjami::getPlayerDuration(id); } void setAutoRestart(const std::string& id, const bool& restart) { libjami::setAutoRestart(id, restart); } private: void registerSignalHandlers() { using namespace std::placeholders; using libjami::exportable_serialized_callback; using libjami::VideoSignal; using libjami::MediaPlayerSignal; using SharedCallback = std::shared_ptr<libjami::CallbackWrapperBase>; const std::map<std::string, SharedCallback> videoEvHandlers = { exportable_serialized_callback<VideoSignal::DeviceEvent>( std::bind(&DBusVideoManager::emitDeviceEvent, this)), exportable_serialized_callback<VideoSignal::DecodingStarted>( std::bind(&DBusVideoManager::emitDecodingStarted, this, _1, _2, _3, _4, _5)), exportable_serialized_callback<VideoSignal::DecodingStopped>( std::bind(&DBusVideoManager::emitDecodingStopped, this, _1, _2, _3)), exportable_serialized_callback<MediaPlayerSignal::FileOpened>( std::bind(&DBusVideoManager::emitFileOpened, this, _1, _2)), }; libjami::registerSignalHandlers(videoEvHandlers); } };
5,785
C++
.h
187
24.919786
98
0.676074
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,855
dbuscallmanager.hpp
savoirfairelinux_jami-daemon/bin/dbus/dbuscallmanager.hpp
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include "dbuscallmanager.adaptor.h" #include <callmanager_interface.h> class DBusCallManager : public sdbus::AdaptorInterfaces<cx::ring::Ring::CallManager_adaptor> { public: DBusCallManager(sdbus::IConnection& connection) : AdaptorInterfaces(connection, "/cx/ring/Ring/CallManager") { registerAdaptor(); registerSignalHandlers(); } ~DBusCallManager() { unregisterAdaptor(); } auto placeCall(const std::string& accountId, const std::string& to) -> decltype(libjami::placeCall(accountId, to)) { return libjami::placeCall(accountId, to); } auto placeCallWithMedia(const std::string& accountId, const std::string& to, const std::vector<std::map<std::string, std::string>>& mediaList) -> decltype(libjami::placeCallWithMedia(accountId, to, mediaList)) { return libjami::placeCallWithMedia(accountId, to, mediaList); } auto requestMediaChange(const std::string& accountId, const std::string& callId, const std::vector<std::map<std::string, std::string>>& mediaList) -> decltype(libjami::requestMediaChange(accountId, callId, mediaList)) { return libjami::requestMediaChange(accountId, callId, mediaList); } auto refuse(const std::string& accountId, const std::string& callId) -> decltype(libjami::refuse(accountId, callId)) { return libjami::refuse(accountId, callId); } auto accept(const std::string& accountId, const std::string& callId) -> decltype(libjami::accept(accountId, callId)) { return libjami::accept(accountId, callId); } auto acceptWithMedia(const std::string& accountId, const std::string& callId, const std::vector<std::map<std::string, std::string>>& mediaList) -> decltype(libjami::acceptWithMedia(accountId, callId, mediaList)) { return libjami::acceptWithMedia(accountId, callId, mediaList); } auto answerMediaChangeRequest( const std::string& accountId, const std::string& callId, const std::vector<std::map<std::string, std::string>>& mediaList) -> decltype(libjami::answerMediaChangeRequest(accountId, callId, mediaList)) { return libjami::answerMediaChangeRequest(accountId, callId, mediaList); } auto hangUp(const std::string& accountId, const std::string& callId) -> decltype(libjami::hangUp(accountId, callId)) { return libjami::hangUp(accountId, callId); } auto hold(const std::string& accountId, const std::string& callId) -> decltype(libjami::hold(accountId, callId)) { return libjami::hold(accountId, callId); } auto unhold(const std::string& accountId, const std::string& callId) -> decltype(libjami::unhold(accountId, callId)) { return libjami::unhold(accountId, callId); } auto muteLocalMedia(const std::string& accountId, const std::string& callId, const std::string& mediaType, const bool& mute) -> decltype(libjami::muteLocalMedia(accountId, callId, mediaType, mute)) { return libjami::muteLocalMedia(accountId, callId, mediaType, mute); } auto transfer(const std::string& accountId, const std::string& callId, const std::string& to) -> decltype(libjami::transfer(accountId, callId, to)) { return libjami::transfer(accountId, callId, to); } auto attendedTransfer(const std::string& accountId, const std::string& callId, const std::string& targetId) -> decltype(libjami::attendedTransfer(accountId, callId, targetId)) { return libjami::attendedTransfer(accountId, callId, targetId); } auto getCallDetails(const std::string& accountId, const std::string& callId) -> decltype(libjami::getCallDetails(accountId, callId)) { return libjami::getCallDetails(accountId, callId); } auto getCallList(const std::string& accountId) -> decltype(libjami::getCallList(accountId)) { return libjami::getCallList(accountId); } std::vector<std::map<std::string, std::string>> getConferenceInfos(const std::string& accountId, const std::string& confId) { return libjami::getConferenceInfos(accountId, confId); } auto joinParticipant(const std::string& accountId, const std::string& sel_callId, const std::string& account2Id, const std::string& drag_callId) -> decltype(libjami::joinParticipant(accountId, sel_callId, account2Id, drag_callId)) { return libjami::joinParticipant(accountId, sel_callId, account2Id, drag_callId); } void createConfFromParticipantList(const std::string& accountId, const std::vector<std::string>& participants) { libjami::createConfFromParticipantList(accountId, participants); } void setConferenceLayout(const std::string& accountId, const std::string& confId, const uint32_t& layout) { libjami::setConferenceLayout(accountId, confId, layout); } void setActiveParticipant(const std::string& accountId, const std::string& confId, const std::string& callId) { libjami::setActiveParticipant(accountId, confId, callId); } void muteStream(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId, const std::string& streamId, const bool& state) { libjami::muteStream(accountId, confId, accountUri, deviceId, streamId, state); } void setActiveStream(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId, const std::string& streamId, const bool& state) { libjami::setActiveStream(accountId, confId, accountUri, deviceId, streamId, state); } void raiseHand(const std::string& accountId, const std::string& confId, const std::string& accountUri, const std::string& deviceId, const bool& state) { libjami::raiseHand(accountId, confId, accountUri, deviceId, state); } auto isConferenceParticipant(const std::string& accountId, const std::string& call_id) -> decltype(libjami::isConferenceParticipant(accountId, call_id)) { return libjami::isConferenceParticipant(accountId, call_id); } auto addParticipant(const std::string& accountId, const std::string& callId, const std::string& account2Id, const std::string& confId) -> decltype(libjami::addParticipant(accountId, callId, account2Id, confId)) { return libjami::addParticipant(accountId, callId, account2Id, confId); } auto addMainParticipant(const std::string& accountId, const std::string& confId) -> decltype(libjami::addMainParticipant(accountId, confId)) { return libjami::addMainParticipant(accountId, confId); } auto detachLocalParticipant() -> decltype(libjami::detachLocalParticipant()) { return libjami::detachLocalParticipant(); } auto detachParticipant(const std::string& accountId, const std::string& callId) -> decltype(libjami::detachParticipant(accountId, callId)) { return libjami::detachParticipant(accountId, callId); } auto joinConference(const std::string& accountId, const std::string& sel_confId, const std::string& account2Id, const std::string& drag_confId) -> decltype(libjami::joinConference(accountId, sel_confId, account2Id, drag_confId)) { return libjami::joinConference(accountId, sel_confId, account2Id, drag_confId); } auto hangUpConference(const std::string& accountId, const std::string& confId) -> decltype(libjami::hangUpConference(accountId, confId)) { return libjami::hangUpConference(accountId, confId); } auto holdConference(const std::string& accountId, const std::string& confId) -> decltype(libjami::holdConference(accountId, confId)) { return libjami::holdConference(accountId, confId); } auto unholdConference(const std::string& accountId, const std::string& confId) -> decltype(libjami::unholdConference(accountId, confId)) { return libjami::unholdConference(accountId, confId); } auto getConferenceList(const std::string& accountId) -> decltype(libjami::getConferenceList(accountId)) { return libjami::getConferenceList(accountId); } auto getParticipantList(const std::string& accountId, const std::string& confId) -> decltype(libjami::getParticipantList(accountId, confId)) { return libjami::getParticipantList(accountId, confId); } auto getConferenceId(const std::string& accountId, const std::string& callId) -> decltype(libjami::getConferenceId(accountId, callId)) { return libjami::getConferenceId(accountId, callId); } auto getConferenceDetails(const std::string& accountId, const std::string& callId) -> decltype(libjami::getConferenceDetails(accountId, callId)) { return libjami::getConferenceDetails(accountId, callId); } auto currentMediaList(const std::string& accountId, const std::string& callId) -> decltype(libjami::currentMediaList(accountId, callId)) { return libjami::currentMediaList(accountId, callId); } auto startRecordedFilePlayback(const std::string& filepath) -> decltype(libjami::startRecordedFilePlayback(filepath)) { return libjami::startRecordedFilePlayback(filepath); } void stopRecordedFilePlayback() { libjami::stopRecordedFilePlayback(); } auto toggleRecording(const std::string& accountId, const std::string& callId) -> decltype(libjami::toggleRecording(accountId, callId)) { return libjami::toggleRecording(accountId, callId); } void setRecording(const std::string& accountId, const std::string& callId) { libjami::setRecording(accountId, callId); } void recordPlaybackSeek(const double& value) { libjami::recordPlaybackSeek(value); } auto getIsRecording(const std::string& accountId, const std::string& callId) -> decltype(libjami::getIsRecording(accountId, callId)) { return libjami::getIsRecording(accountId, callId); } bool switchInput(const std::string& accountId, const std::string& callId, const std::string& input) { return libjami::switchInput(accountId, callId, input); } bool switchSecondaryInput(const std::string& accountId, const std::string& conferenceId, const std::string& input) { return libjami::switchSecondaryInput(accountId, conferenceId, input); } void playDTMF(const std::string& key) { libjami::playDTMF(key); } void startTone(const int32_t& start, const int32_t& type) { libjami::startTone(start, type); } void sendTextMessage(const std::string& accountId, const std::string& callId, const std::map<std::string, std::string>& messages, const bool& isMixed) { libjami::sendTextMessage(accountId, callId, messages, "Me", isMixed); } void startSmartInfo(const uint32_t& refreshTimeMs) { libjami::startSmartInfo(refreshTimeMs); } void stopSmartInfo() { libjami::stopSmartInfo(); } void setModerator(const std::string& accountId, const std::string& confId, const std::string& peerId, const bool& state) { libjami::setModerator(accountId, confId, peerId, state); } void muteParticipant(const std::string& accountId, const std::string& confId, const std::string& peerId, const bool& state) { libjami::muteParticipant(accountId, confId, peerId, state); } void hangupParticipant(const std::string& accountId, const std::string& confId, const std::string& peerId, const std::string& deviceId) { libjami::hangupParticipant(accountId, confId, peerId, deviceId); } void raiseParticipantHand(const std::string& accountId, const std::string& confId, const std::string& peerId, const bool& state) { libjami::raiseParticipantHand(accountId, confId, peerId, state); } private: void registerSignalHandlers() { using namespace std::placeholders; using libjami::exportable_serialized_callback; using libjami::CallSignal; using SharedCallback = std::shared_ptr<libjami::CallbackWrapperBase>; const std::map<std::string, SharedCallback> callEvHandlers = {exportable_serialized_callback<CallSignal::StateChange>( std::bind(&DBusCallManager::emitCallStateChanged, this, _1, _2, _3, _4)), exportable_serialized_callback<CallSignal::TransferFailed>( std::bind(&DBusCallManager::emitTransferFailed, this)), exportable_serialized_callback<CallSignal::TransferSucceeded>( std::bind(&DBusCallManager::emitTransferSucceeded, this)), exportable_serialized_callback<CallSignal::RecordPlaybackStopped>( std::bind(&DBusCallManager::emitRecordPlaybackStopped, this, _1)), exportable_serialized_callback<CallSignal::VoiceMailNotify>( std::bind(&DBusCallManager::emitVoiceMailNotify, this, _1, _2, _3, _4)), exportable_serialized_callback<CallSignal::IncomingMessage>( std::bind(&DBusCallManager::emitIncomingMessage, this, _1, _2, _3, _4)), exportable_serialized_callback<CallSignal::IncomingCall>( std::bind(&DBusCallManager::emitIncomingCall, this, _1, _2, _3)), exportable_serialized_callback<CallSignal::IncomingCallWithMedia>( std::bind(&DBusCallManager::emitIncomingCallWithMedia, this, _1, _2, _3, _4)), exportable_serialized_callback<CallSignal::MediaChangeRequested>( std::bind(&DBusCallManager::emitMediaChangeRequested, this, _1, _2, _3)), exportable_serialized_callback<CallSignal::RecordPlaybackFilepath>( std::bind(&DBusCallManager::emitRecordPlaybackFilepath, this, _1, _2)), exportable_serialized_callback<CallSignal::ConferenceCreated>( std::bind(&DBusCallManager::emitConferenceCreated, this, _1, _2, _3)), exportable_serialized_callback<CallSignal::ConferenceChanged>( std::bind(&DBusCallManager::emitConferenceChanged, this, _1, _2, _3)), exportable_serialized_callback<CallSignal::UpdatePlaybackScale>( std::bind(&DBusCallManager::emitUpdatePlaybackScale, this, _1, _2, _3)), exportable_serialized_callback<CallSignal::ConferenceRemoved>( std::bind(&DBusCallManager::emitConferenceRemoved, this, _1, _2)), exportable_serialized_callback<CallSignal::RecordingStateChanged>( std::bind(&DBusCallManager::emitRecordingStateChanged, this, _1, _2)), exportable_serialized_callback<CallSignal::RtcpReportReceived>( std::bind(&DBusCallManager::emitOnRtcpReportReceived, this, _1, _2)), exportable_serialized_callback<CallSignal::OnConferenceInfosUpdated>( std::bind(&DBusCallManager::emitOnConferenceInfosUpdated, this, _1, _2)), exportable_serialized_callback<CallSignal::PeerHold>( std::bind(&DBusCallManager::emitPeerHold, this, _1, _2)), exportable_serialized_callback<CallSignal::AudioMuted>( std::bind(&DBusCallManager::emitAudioMuted, this, _1, _2)), exportable_serialized_callback<CallSignal::VideoMuted>( std::bind(&DBusCallManager::emitVideoMuted, this, _1, _2)), exportable_serialized_callback<CallSignal::SmartInfo>( std::bind(&DBusCallManager::emitSmartInfo, this, _1)), exportable_serialized_callback<CallSignal::RemoteRecordingChanged>( std::bind(&DBusCallManager::emitRemoteRecordingChanged, this, _1, _2, _3)), exportable_serialized_callback<CallSignal::MediaNegotiationStatus>( std::bind(&DBusCallManager::emitMediaNegotiationStatus, this, _1, _2, _3)) }; libjami::registerSignalHandlers(callEvHandlers); } };
18,519
C++
.h
455
31.375824
98
0.638171
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,856
callback.h
savoirfairelinux_jami-daemon/bin/nodejs/callback.h
#pragma once #include <uv.h> #include <queue> #include <functional> #include <mutex> #include <string_view> using namespace v8; Persistent<Function> accountsChangedCb; Persistent<Function> accountDetailsChangedCb; Persistent<Function> registrationStateChangedCb; Persistent<Function> composingStatusChangedCb; Persistent<Function> volatileDetailsChangedCb; Persistent<Function> incomingAccountMessageCb; Persistent<Function> accountMessageStatusChangedCb; Persistent<Function> needsHostCb; Persistent<Function> activeCallsChangedCb; Persistent<Function> incomingTrustRequestCb; Persistent<Function> contactAddedCb; Persistent<Function> contactRemovedCb; Persistent<Function> exportOnRingEndedCb; Persistent<Function> nameRegistrationEndedCb; Persistent<Function> knownDevicesChangedCb; Persistent<Function> registeredNameFoundCb; Persistent<Function> callStateChangedCb; Persistent<Function> mediaChangeRequestedCb; Persistent<Function> incomingMessageCb; Persistent<Function> incomingCallCb; Persistent<Function> incomingCallWithMediaCb; Persistent<Function> dataTransferEventCb; Persistent<Function> conversationLoadedCb; Persistent<Function> swarmLoadedCb; Persistent<Function> messagesFoundCb; Persistent<Function> messageReceivedCb; Persistent<Function> swarmMessageReceivedCb; Persistent<Function> swarmMessageUpdatedCb; Persistent<Function> reactionAddedCb; Persistent<Function> reactionRemovedCb; Persistent<Function> conversationProfileUpdatedCb; Persistent<Function> conversationRequestReceivedCb; Persistent<Function> conversationRequestDeclinedCb; Persistent<Function> conversationReadyCb; Persistent<Function> conversationRemovedCb; Persistent<Function> conversationMemberEventCb; Persistent<Function> onConversationErrorCb; Persistent<Function> conferenceCreatedCb; Persistent<Function> conferenceChangedCb; Persistent<Function> conferenceRemovedCb; Persistent<Function> onConferenceInfosUpdatedCb; Persistent<Function> conversationPreferencesUpdatedCb; Persistent<Function> messageSendCb; Persistent<Function> accountProfileReceivedCb; Persistent<Function> profileReceivedCb; std::queue<std::function<void()>> pendingSignals; std::mutex pendingSignalsLock; uv_async_t signalAsync; Persistent<Function>* getPresistentCb(std::string_view signal) { if (signal == "AccountsChanged") return &accountsChangedCb; else if (signal == "AccountDetailsChanged") return &accountDetailsChangedCb; else if (signal == "RegistrationStateChanged") return &registrationStateChangedCb; else if (signal == "ComposingStatusChanged") return &composingStatusChangedCb; else if (signal == "VolatileDetailsChanged") return &volatileDetailsChangedCb; else if (signal == "IncomingAccountMessage") return &incomingAccountMessageCb; else if (signal == "AccountMessageStatusChanged") return &accountMessageStatusChangedCb; else if (signal == "NeedsHost") return &needsHostCb; else if (signal == "ActiveCallsChanged") return &activeCallsChangedCb; else if (signal == "IncomingTrustRequest") return &incomingTrustRequestCb; else if (signal == "ContactAdded") return &contactAddedCb; else if (signal == "ContactRemoved") return &contactRemovedCb; else if (signal == "ExportOnRingEnded") return &exportOnRingEndedCb; else if (signal == "NameRegistrationEnded") return &nameRegistrationEndedCb; else if (signal == "KnownDevicesChanged") return &knownDevicesChangedCb; else if (signal == "RegisteredNameFound") return &registeredNameFoundCb; else if (signal == "CallStateChanged") return &callStateChangedCb; else if (signal == "MediaChangeRequested") return &mediaChangeRequestedCb; else if (signal == "IncomingMessage") return &incomingMessageCb; else if (signal == "IncomingCall") return &incomingCallCb; else if (signal == "IncomingCallWithMedia") return &incomingCallWithMediaCb; else if (signal == "DataTransferEvent") return &dataTransferEventCb; else if (signal == "ConversationLoaded") return &conversationLoadedCb; else if (signal == "SwarmLoaded") return &swarmLoadedCb; else if (signal == "MessagesFound") return &messagesFoundCb; else if (signal == "MessageReceived") return &messageReceivedCb; else if (signal == "SwarmMessageReceived") return &swarmMessageReceivedCb; else if (signal == "SwarmMessageUpdated") return &swarmMessageUpdatedCb; else if (signal == "ReactionAdded") return &reactionAddedCb; else if (signal == "ReactionRemoved") return &reactionRemovedCb; else if (signal == "ConversationProfileUpdated") return &conversationProfileUpdatedCb; else if (signal == "ConversationReady") return &conversationReadyCb; else if (signal == "ConversationRemoved") return &conversationRemovedCb; else if (signal == "ConversationRequestReceived") return &conversationRequestReceivedCb; else if (signal == "ConversationRequestDeclined") return &conversationRequestDeclinedCb; else if (signal == "ConversationMemberEvent") return &conversationMemberEventCb; else if (signal == "OnConversationError") return &onConversationErrorCb; else if (signal == "ConferenceCreated") return &conferenceCreatedCb; else if (signal == "ConferenceChanged") return &conferenceChangedCb; else if (signal == "ConferenceRemoved") return &conferenceRemovedCb; else if (signal == "OnConferenceInfosUpdated") return &onConferenceInfosUpdatedCb; else if (signal == "ConversationPreferencesUpdated") return &conversationPreferencesUpdatedCb; else if (signal == "LogMessage") return &messageSendCb; else if (signal == "AccountProfileReceived") return &accountProfileReceivedCb; else if (signal == "ProfileReceived") return &profileReceivedCb; else return nullptr; } #define V8_STRING_LITERAL(str) \ v8::String::NewFromUtf8Literal(v8::Isolate::GetCurrent(), str) #define V8_STRING_NEW(str) \ v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), \ str.data(), \ v8::NewStringType::kNormal, \ str.size()) #define V8_STRING_NEW_LOCAL(str) V8_STRING_NEW(str).ToLocalChecked() inline std::string_view toView(const String::Utf8Value& utf8) { return {*utf8, (size_t) utf8.length()}; } inline SWIGV8_ARRAY intVectToJsArray(const std::vector<uint8_t>& intVect) { SWIGV8_ARRAY jsArray = SWIGV8_ARRAY_NEW(intVect.size()); for (unsigned int i = 0; i < intVect.size(); i++) jsArray->Set(SWIGV8_CURRENT_CONTEXT(), SWIGV8_INTEGER_NEW_UNS(i), SWIGV8_INTEGER_NEW(intVect[i])); return jsArray; } inline SWIGV8_OBJECT stringMapToJsMap(const std::map<std::string, std::string>& strmap) { SWIGV8_OBJECT jsMap = SWIGV8_OBJECT_NEW(); for (auto& kvpair : strmap) jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_NEW_LOCAL(std::get<0>(kvpair)), V8_STRING_NEW_LOCAL(std::get<1>(kvpair))); return jsMap; } inline SWIGV8_OBJECT stringIntMapToJsMap(const std::map<std::string, int32_t>& strmap) { SWIGV8_OBJECT jsMap = SWIGV8_OBJECT_NEW(); for (auto& kvpair : strmap) jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_NEW_LOCAL(std::get<0>(kvpair)), SWIGV8_INTEGER_NEW(std::get<1>(kvpair))); return jsMap; } inline SWIGV8_ARRAY stringMapVecToJsMapArray(const std::vector<std::map<std::string, std::string>>& vect) { SWIGV8_ARRAY jsArray = SWIGV8_ARRAY_NEW(vect.size()); for (unsigned int i = 0; i < vect.size(); i++) jsArray->Set(SWIGV8_CURRENT_CONTEXT(), SWIGV8_INTEGER_NEW_UNS(i), stringMapToJsMap(vect[i])); return jsArray; } inline SWIGV8_OBJECT swarmMessageToJs(const libjami::SwarmMessage& message) { SWIGV8_OBJECT jsMap = SWIGV8_OBJECT_NEW(); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("id"), V8_STRING_NEW_LOCAL(message.id)); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("type"), V8_STRING_NEW_LOCAL(message.type)); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("linearizedParent"), V8_STRING_NEW_LOCAL(message.linearizedParent)); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("body"), stringMapToJsMap(message.body)); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("reactions"), stringMapVecToJsMapArray(message.reactions)); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("editions"), stringMapVecToJsMapArray(message.editions)); jsMap->Set(SWIGV8_CURRENT_CONTEXT(), V8_STRING_LITERAL("status"), stringIntMapToJsMap(message.status)); return jsMap; } inline SWIGV8_ARRAY swarmMessagesToJsArray(const std::vector<libjami::SwarmMessage>& messages) { SWIGV8_ARRAY jsArray = SWIGV8_ARRAY_NEW(messages.size()); for (unsigned int i = 0; i < messages.size(); i++) jsArray->Set(SWIGV8_CURRENT_CONTEXT(), SWIGV8_INTEGER_NEW_UNS(i), swarmMessageToJs(messages[i])); return jsArray; } void setCallback(std::string_view signal, Local<Function>& func) { if (auto* presistentCb = getPresistentCb(signal)) { if (func->IsObject() && func->IsFunction()) { presistentCb->Reset(Isolate::GetCurrent(), func); } else { presistentCb->Reset(); } } else { printf("No Signal Associated with Event \'%.*s\'\n", (int) signal.size(), signal.data()); } } void parseCbMap(const SWIGV8_VALUE& callbackMap) { SWIGV8_OBJECT cbAssocArray = callbackMap->ToObject(SWIGV8_CURRENT_CONTEXT()).ToLocalChecked(); SWIGV8_ARRAY props = cbAssocArray->GetOwnPropertyNames(SWIGV8_CURRENT_CONTEXT()).ToLocalChecked(); for (uint32_t i = 0; i < props->Length(); ++i) { SWIGV8_VALUE key_local = props->Get(SWIGV8_CURRENT_CONTEXT(), i).ToLocalChecked(); auto utf8Value = String::Utf8Value(Isolate::GetCurrent(), key_local); SWIGV8_OBJECT buffer = cbAssocArray->Get(SWIGV8_CURRENT_CONTEXT(), key_local) .ToLocalChecked() ->ToObject(SWIGV8_CURRENT_CONTEXT()) .ToLocalChecked(); Local<Function> func = Local<Function>::Cast(buffer); setCallback(toView(utf8Value), func); } } void handlePendingSignals(uv_async_t* async_data) { SWIGV8_HANDLESCOPE(); std::lock_guard lock(pendingSignalsLock); while (not pendingSignals.empty()) { pendingSignals.front()(); pendingSignals.pop(); } } void registrationStateChanged(const std::string& accountId, const std::string& state, int code, const std::string& detail_str) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, state, code, detail_str]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), registrationStateChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(state), SWIGV8_INTEGER_NEW(code), V8_STRING_NEW_LOCAL(detail_str)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void composingStatusChanged(const std::string& accountId, const std::string& conversationId, const std::string& from, int state) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, from, state]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), composingStatusChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), V8_STRING_NEW_LOCAL(from), SWIGV8_INTEGER_NEW(state)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void volatileDetailsChanged(const std::string& accountId, const std::map<std::string, std::string>& details) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, details]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), volatileDetailsChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), stringMapToJsMap(details)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void accountDetailsChanged(const std::string& accountId, const std::map<std::string, std::string>& details) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, details]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), accountDetailsChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), stringMapToJsMap(details)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void accountsChanged() { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), accountsChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 0, callback_args); } }); uv_async_send(&signalAsync); } void contactAdded(const std::string& accountId, const std::string& uri, bool confirmed) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, uri, confirmed]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), contactAddedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(uri), SWIGV8_BOOLEAN_NEW(confirmed)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void contactRemoved(const std::string& accountId, const std::string& uri, bool banned) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, uri, banned]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), contactRemovedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(uri), SWIGV8_BOOLEAN_NEW(banned)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void exportOnRingEnded(const std::string& accountId, int state, const std::string& pin) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, state, pin]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), exportOnRingEndedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), SWIGV8_INTEGER_NEW(state), V8_STRING_NEW_LOCAL(pin)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void nameRegistrationEnded(const std::string& accountId, int state, const std::string& name) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, state, name]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), nameRegistrationEndedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), SWIGV8_INTEGER_NEW(state), V8_STRING_NEW_LOCAL(name)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void registeredNameFound(const std::string& accountId, int state, const std::string& address, const std::string& name) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, state, address, name]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), registeredNameFoundCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), SWIGV8_INTEGER_NEW(state), V8_STRING_NEW_LOCAL(address), V8_STRING_NEW_LOCAL(name)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void accountMessageStatusChanged(const std::string& account_id, const std::string& conversationId, const std::string& peer, const std::string& message_id, int state) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([account_id, message_id, peer, state]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), accountMessageStatusChangedCb); if (!func.IsEmpty()) { Local<Value> callback_args[] = {V8_STRING_NEW_LOCAL(account_id), V8_STRING_NEW_LOCAL(message_id), V8_STRING_NEW_LOCAL(peer), SWIGV8_INTEGER_NEW(state)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void needsHost(const std::string& account_id, const std::string& conversationId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([account_id, conversationId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), needsHostCb); if (!func.IsEmpty()) { Local<Value> callback_args[] = {V8_STRING_NEW_LOCAL(account_id), V8_STRING_NEW_LOCAL(conversationId)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void activeCallsChanged(const std::string& account_id, const std::string& conversationId, const std::vector<std::map<std::string, std::string>>& activeCalls) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([account_id, conversationId, activeCalls]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), activeCallsChangedCb); if (!func.IsEmpty()) { Local<Value> callback_args[] = {V8_STRING_NEW_LOCAL(account_id), V8_STRING_NEW_LOCAL(conversationId), stringMapVecToJsMapArray(activeCalls)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void incomingAccountMessage(const std::string& accountId, const std::string& messageId, const std::string& from, const std::map<std::string, std::string>& payloads) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, from, payloads]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), incomingAccountMessageCb); if (!func.IsEmpty()) { SWIGV8_OBJECT jsMap = stringMapToJsMap(payloads); SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(from), jsMap}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void knownDevicesChanged(const std::string& accountId, const std::map<std::string, std::string>& devices) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, devices]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), knownDevicesChangedCb); if (!func.IsEmpty()) { SWIGV8_OBJECT jsMap = stringMapToJsMap(devices); SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), jsMap}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void incomingTrustRequest(const std::string& accountId, const std::string& from, const std::vector<uint8_t>& payload, time_t received) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, from, payload, received]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), incomingTrustRequestCb); if (!func.IsEmpty()) { SWIGV8_ARRAY jsArray = intVectToJsArray(payload); SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(from), jsArray, SWIGV8_NUMBER_NEW(received)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void callStateChanged(const std::string& accountId, const std::string& callId, const std::string& state, int detail_code) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, callId, state, detail_code]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), callStateChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(callId), V8_STRING_NEW_LOCAL(state), SWIGV8_INTEGER_NEW(detail_code)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void mediaChangeRequested(const std::string& accountId, const std::string& callId, const std::vector<std::map<std::string, std::string>>& mediaList) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, callId, mediaList]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), mediaChangeRequestedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(callId), stringMapVecToJsMapArray(mediaList)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void incomingMessage(const std::string& accountId, const std::string& id, const std::string& from, const std::map<std::string, std::string>& messages) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, id, from, messages]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), incomingMessageCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(id), V8_STRING_NEW_LOCAL(from), stringMapToJsMap(messages)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void incomingCall(const std::string& accountId, const std::string& callId, const std::string& from) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, callId, from]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), incomingCallCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(callId), V8_STRING_NEW_LOCAL(from)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void incomingCallWithMedia(const std::string& accountId, const std::string& callId, const std::string& from, const std::vector<std::map<std::string, std::string>>& mediaList) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, callId, from, mediaList]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), incomingCallWithMediaCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(callId), V8_STRING_NEW_LOCAL(from), stringMapVecToJsMapArray(mediaList)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } /** Data Transfer */ void dataTransferEvent(const std::string& accountId, const std::string& conversationId, const std::string& interactionId, const std::string& fileId, int eventCode) { std::lock_guard<std::mutex> lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, interactionId, fileId, eventCode]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), dataTransferEventCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), V8_STRING_NEW_LOCAL(interactionId), V8_STRING_NEW_LOCAL(fileId), SWIGV8_INTEGER_NEW(eventCode)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 5, callback_args); } }); uv_async_send(&signalAsync); } /** Conversations */ void conversationLoaded(uint32_t id, const std::string& accountId, const std::string& conversationId, const std::vector<std::map<std::string, std::string>>& message) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([id, accountId, conversationId, message]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationLoadedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {SWIGV8_INTEGER_NEW_UNS(id), V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), stringMapVecToJsMapArray(message)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void swarmLoaded(uint32_t id, const std::string& accountId, const std::string& conversationId, const std::vector<libjami::SwarmMessage>& messages) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([id, accountId, conversationId, messages]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), swarmLoadedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {SWIGV8_INTEGER_NEW_UNS(id), V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), swarmMessagesToJsArray(messages)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void swarmMessageReceived(const std::string& accountId, const std::string& conversationId, const libjami::SwarmMessage& message) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, message]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), swarmMessageReceivedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), swarmMessageToJs(message)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void swarmMessageUpdated(const std::string& accountId, const std::string& conversationId, const libjami::SwarmMessage& message) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, message]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), swarmMessageUpdatedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), swarmMessageToJs(message)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void reactionAdded(const std::string& accountId, const std::string& conversationId, const std::string& messageId, const std::map<std::string, std::string>& reaction) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, messageId, reaction]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), reactionAddedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), V8_STRING_NEW_LOCAL(messageId), stringMapToJsMap(reaction)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void reactionRemoved(const std::string& accountId, const std::string& conversationId, const std::string& messageId, const std::string& reactionId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, messageId, reactionId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), reactionRemovedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), V8_STRING_NEW_LOCAL(messageId), V8_STRING_NEW_LOCAL(reactionId)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void messagesFound(uint32_t id, const std::string& accountId, const std::string& conversationId, const std::vector<std::map<std::string, std::string>>& messages) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([id, accountId, conversationId, messages]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), messagesFoundCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {SWIGV8_INTEGER_NEW_UNS(id), V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), stringMapVecToJsMapArray(messages)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void messageReceived(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& message) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, message]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), messageReceivedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), stringMapToJsMap(message)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void conversationProfileUpdated(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& profile) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, profile]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationProfileUpdatedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), stringMapToJsMap(profile)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void conversationRequestReceived(const std::string& accountId, const std::string& conversationId, const std::map<std::string, std::string>& message) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, message]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationRequestReceivedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), stringMapToJsMap(message)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void conversationRequestDeclined(const std::string& accountId, const std::string& conversationId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationRequestDeclinedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void conversationReady(const std::string& accountId, const std::string& conversationId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationReadyCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = { V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), }; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void conversationRemoved(const std::string& accountId, const std::string& conversationId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationRemovedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = { V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), }; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void conversationMemberEvent(const std::string& accountId, const std::string& conversationId, const std::string& memberUri, int event) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, memberUri, event]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationMemberEventCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), V8_STRING_NEW_LOCAL(memberUri), SWIGV8_INTEGER_NEW(event)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void onConversationError(const std::string& accountId, const std::string& conversationId, uint32_t code, const std::string& what) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, conversationId, code, what]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), onConversationErrorCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), SWIGV8_INTEGER_NEW_UNS(code), V8_STRING_NEW_LOCAL(what)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 4, callback_args); } }); uv_async_send(&signalAsync); } void conferenceCreated(const std::string& accountId, const std::string& conversationId, const std::string& confId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, confId, conversationId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conferenceCreatedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(conversationId), V8_STRING_NEW_LOCAL(confId)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void conferenceChanged(const std::string& accountId, const std::string& confId, const std::string& state) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, confId, state]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conferenceChangedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(confId), V8_STRING_NEW_LOCAL(state)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void conferenceRemoved(const std::string& accountId, const std::string& confId) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, confId]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conferenceRemovedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(confId)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 2, callback_args); } }); uv_async_send(&signalAsync); } void onConferenceInfosUpdated(const std::string& accountId, const std::string& confId, const std::vector<std::map<std::string, std::string>>& infos) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, confId, infos]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), onConferenceInfosUpdatedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(confId), stringMapVecToJsMapArray(infos)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void conversationPreferencesUpdated(const std::string& accountId, const std::string& convId, const std::map<std::string, std::string>& preferences) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, convId, preferences]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), conversationPreferencesUpdatedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(convId), stringMapToJsMap(preferences)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void logMessage(const std::string& message) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([message]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), messageSendCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(message)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 1, callback_args); } }); uv_async_send(&signalAsync); } void accountProfileReceived(const std::string& accountId, const std::string& displayName, const std::string& photo) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, displayName, photo]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), accountProfileReceivedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(displayName), V8_STRING_NEW_LOCAL(photo)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); } void profileReceived(const std::string& accountId, const std::string& from, const std::string& path) { std::lock_guard lock(pendingSignalsLock); pendingSignals.emplace([accountId, from, path]() { Local<Function> func = Local<Function>::New(Isolate::GetCurrent(), profileReceivedCb); if (!func.IsEmpty()) { SWIGV8_VALUE callback_args[] = {V8_STRING_NEW_LOCAL(accountId), V8_STRING_NEW_LOCAL(from), V8_STRING_NEW_LOCAL(path)}; func->Call(SWIGV8_CURRENT_CONTEXT(), SWIGV8_NULL(), 3, callback_args); } }); uv_async_send(&signalAsync); }
46,060
C++
.h
1,035
33.540097
127
0.604054
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,857
test_runner.h
savoirfairelinux_jami-daemon/test/test_runner.h
#include <iostream> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> #include <cppunit/CompilerOutputter.h> #define RING_TEST_RUNNER(suite_name) \ int main() \ { \ CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry( \ suite_name); \ CppUnit::Test* suite = registry.makeTest(); \ if (suite->countTestCases() == 0) { \ std::cout << "No test cases specified for suite \"" << suite_name << "\"\n"; \ return 1; \ } \ CppUnit::TextUi::TestRunner runner; \ runner.addTest(suite); \ return runner.run() ? 0 : 1; \ } // This version of the test runner is similar to RING_TEST_RUNNER but // can take multiple unit tests. // It's practical to run a test for diffrent configs, for instance when // running the same test for both Jami and SIP accounts. // The test will abort if a test fails. #define JAMI_TEST_RUNNER(...) \ int main() \ { \ std::vector<std::string> suite_names {__VA_ARGS__}; \ for (const std::string& name : suite_names) { \ CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry( \ name); \ CppUnit::Test* suite = registry.makeTest(); \ if (suite->countTestCases() == 0) { \ std::cout << "No test cases specified for suite \"" << name << "\"\n"; \ continue; \ } \ CppUnit::TextUi::TestRunner runner; \ runner.addTest(suite); \ if (not runner.run()) \ return 1; \ } \ return 0; \ }
1,691
C++
.h
42
32.119048
97
0.581155
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,858
common.h
savoirfairelinux_jami-daemon/test/fuzzing/common.h
#pragma once #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <cassert> #include <cstdint> #include <cstring> #include <vector> #include <dlfcn.h> static inline bool streq(const char* A, const char* B) { return 0 == strcmp(A, B); } #define BEGIN_WRAPPER_PRIMITIVE(SYM, RET, NAME, ARGS...) \ RET NAME(ARGS) \ { \ RET (*this_func)(ARGS) = nullptr; \ \ if (nullptr == this_func) { \ this_func = (typeof(this_func)) dlsym(RTLD_NEXT, #SYM); \ assert(this_func); \ } #define BEGIN_METHOD_WRAPPER(SYM, RET, NAME, ARGS...) \ RET NAME(ARGS) \ { \ RET (*this_func)(typeof(this), ##ARGS) = nullptr; \ \ if (nullptr == this_func) { \ this_func = (typeof(this_func)) dlsym(RTLD_NEXT, #SYM); \ assert(this_func); \ } #define BEGIN_WRAPPER(RET, NAME, ARGS...) BEGIN_WRAPPER_PRIMITIVE(NAME, RET, NAME, ARGS) #define END_WRAPPER(ARGS...) } static_assert(true, "") #define __weak __attribute__((weak)) #define __used __attribute__((used)) #define array_size(arr) (sizeof(arr) / sizeof((arr)[0]))
1,737
C++
.h
37
37.702703
88
0.382022
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,859
utils.h
savoirfairelinux_jami-daemon/test/fuzzing/lib/utils.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <chrono> #include <cstdint> #include <map> #include <string> #include <filesystem> #include <vector> constexpr size_t WAIT_FOR_ANNOUNCEMENT_TIMEOUT = 30; constexpr size_t WAIT_FOR_REMOVAL_TIMEOUT = 30; extern void wait_for_announcement_of(const std::vector<std::string> accountIDs, std::chrono::seconds timeout = std::chrono::seconds(WAIT_FOR_ANNOUNCEMENT_TIMEOUT)); extern void wait_for_announcement_of(const std::string& accountId, std::chrono::seconds timeout = std::chrono::seconds(WAIT_FOR_ANNOUNCEMENT_TIMEOUT)); extern void wait_for_removal_of(const std::vector<std::string> accounts, std::chrono::seconds timeout = std::chrono::seconds(WAIT_FOR_REMOVAL_TIMEOUT)); extern void wait_for_removal_of(const std::string& account, std::chrono::seconds timeout = std::chrono::seconds(WAIT_FOR_REMOVAL_TIMEOUT)); extern std::map<std::string, std::string> load_actors(const std::filesystem::path& from_yaml); extern std::map<std::string, std::string> load_actors_and_wait_for_announcement(const std::string& from_yaml);
1,855
C++
.h
41
41.487805
109
0.730343
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,860
gnutls.h
savoirfairelinux_jami-daemon/test/fuzzing/lib/gnutls.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <gnutls/gnutls.h> #include <gnutls/dtls.h> #include <msgpack.hpp> /* TODO - Import this from jami */ struct ChanneledMessage { uint16_t channel; std::vector<uint8_t> data; MSGPACK_DEFINE(channel, data) }; extern "C" { extern void inject_into_gnutls(const ChanneledMessage& msg); extern void post_gnutls_init_hook(gnutls_session_t session); extern void pre_gnutls_deinit_hook(gnutls_session_t session); extern void pre_mutate_gnutls_record_send_hook(const ChanneledMessage& msg); extern void post_mutate_gnutls_record_send_hook(const ChanneledMessage& msg, bool hasMutated); extern bool mutate_gnutls_record_send(ChanneledMessage& msg); extern void pre_mutate_gnutls_record_recv_hook(const ChanneledMessage& msg); extern void post_mutate_gnutls_record_recv_hook(const ChanneledMessage& msg, bool hasMutated); extern bool mutate_gnutls_record_recv(ChanneledMessage& msg); };
1,633
C++
.h
38
41.026316
94
0.775536
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,861
syslog.h
savoirfairelinux_jami-daemon/test/fuzzing/lib/syslog.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once #include <stdarg.h> extern "C" { extern bool syslog_handler(int priority, const char *fmt, va_list ap); };
840
C++
.h
21
38.142857
73
0.74541
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,862
sip-fmt.h
savoirfairelinux_jami-daemon/test/fuzzing/lib/sip-fmt.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <vector> #include <iostream> #include <string> #include <map> class SIPFmt { public: SIPFmt(const std::vector<uint8_t>& data); bool parse(const std::vector<uint8_t>& blob); void pushBody(char *bytes, size_t len); const std::string& getField(const std::string& field) const ; const std::vector<uint8_t>& getBody(); void setVersion(const std::string& version) { version_ = version; } void setField(const std::string& field); void setFieldValue(const std::string& field, const std::string& value); void setMethod(const std::string& method) { method_ = method; } void setURI(const std::string& URI) { URI_ = URI; } void setStatus(const std::string& status) { status_ = status; } void setMsg(const std::string& msg) { msg_ = msg; } void swapBody(std::vector<uint8_t>& body); bool isValid() const { return isValid_; } bool isRequest() const { return isValid_ and isRequest_; } bool isResponse() const { return isValid_ and not isRequest_; } bool isApplication(const std::string& app) const { return isValid() and (std::string::npos != getField("content-type").find("application/" + app)); } void setAsRequest() { isRequest_ = true; }; void setAsResponse() { isRequest_ = false; }; void swap(std::vector<uint8_t>& with); private: std::vector<uint8_t> body_ {}; std::string status_ {}; std::string version_ {}; std::string msg_ {}; std::string URI_ {}; std::string method_ {}; std::map<std::string, std::string> fields_ {}; bool isValid_; bool isRequest_ {}; };
2,327
C++
.h
57
36.982456
106
0.682322
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,863
supervisor.h
savoirfairelinux_jami-daemon/test/fuzzing/lib/supervisor.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #pragma once namespace supervisor { namespace signal { enum exit { log = 1, }; }; namespace env { extern const char* log; extern const char* tls_out; }; // namespace env }; // namespace supervisor
924
C++
.h
28
31.107143
73
0.74382
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,864
classic-alice-and-bob.h
savoirfairelinux_jami-daemon/test/fuzzing/scenarios/classic-alice-and-bob.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <condition_variable> #include "manager.h" #include "connectivity/connectionmanager.h" #include "jamidht/jamiaccount.h" #include "jami.h" #include "account_const.h" #include "lib/utils.h" int main(void) { libjami::init(libjami::InitFlag(libjami::LIBJAMI_FLAG_DEBUG | libjami::LIBJAMI_FLAG_CONSOLE_LOG)); if (not jami::Manager::instance().initialized) { assert(libjami::start("dring-sample.yml")); } auto actors = load_actors_and_wait_for_announcement("actors/alice-bob.yml"); auto alice = actors["alice"]; auto bob = actors["bob"]; auto aliceAccount = jami::Manager::instance().getAccount<jami::JamiAccount>(alice); auto bobAccount = jami::Manager::instance().getAccount<jami::JamiAccount>(bob); auto aliceUri = aliceAccount->getUsername(); auto bobUri = bobAccount->getUsername(); std::map<std::string, std::shared_ptr<libjami::CallbackWrapperBase>> confHandlers; std::atomic_bool callReceived {false}; std::mutex mtx; std::unique_lock lk {mtx}; std::condition_variable cv; confHandlers.insert(libjami::exportable_callback<libjami::CallSignal::IncomingCall>( [&](const std::string&, const std::string&, const std::string&) { callReceived = true; cv.notify_one(); })); libjami::registerSignalHandlers(confHandlers); auto call = aliceAccount->newOutgoingCall(bobUri); assert(cv.wait_for(lk, std::chrono::seconds(30), [&] { return callReceived.load(); })); std::this_thread::sleep_for(std::chrono::seconds(60)); wait_for_removal_of({alice, bob}); libjami::fini(); return 0; }
2,579
C++
.h
54
39.555556
106
0.647387
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
751,865
test_SIP.h
savoirfairelinux_jami-daemon/test/sip/test_SIP.h
/* * Copyright (C) 2004-2024 Savoir-faire Linux Inc. * * 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 * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // Cppunit import #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCaller.h> #include <cppunit/TestCase.h> #include <cppunit/TestSuite.h> // Application import #include "manager.h" #include "sip/sipvoiplink.h" #include "connectivity/sip_utils.h" #include <atomic> #include <thread> class RAIIThread { public: RAIIThread() = default; RAIIThread(std::thread&& t) : thread_ {std::move(t)} {}; ~RAIIThread() { join(); } void join() { if (thread_.joinable()) thread_.join(); } RAIIThread(RAIIThread&&) = default; RAIIThread& operator=(RAIIThread&&) = default; private: std::thread thread_; }; /* * @file Test-sip.h * @brief Regroups unitary tests related to the SIP module */ class test_SIP : public CppUnit::TestFixture { public: /* * Code factoring - Common resources can be initialized here. * This method is called by unitcpp before each test */ void setUp(); /* * Code factoring - Common resources can be released here. * This method is called by unitcpp after each test */ void tearDown(); private: void testSIPURI(void); /** * Use cppunit library macros to add unit test to the factory */ CPPUNIT_TEST_SUITE(test_SIP); CPPUNIT_TEST(testSIPURI); CPPUNIT_TEST_SUITE_END(); RAIIThread eventLoop_; std::atomic_bool running_; };
2,150
C++
.h
74
25.581081
73
0.698058
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false