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,966
accel.h
savoirfairelinux_jami-daemon/src/media/video/accel.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 "libav_deps.h" #include "media_codec.h" #include <memory> #include <string> #include <vector> #include <list> extern "C" { #include <libavutil/hwcontext.h> } namespace jami { namespace video { enum class DeviceState { NOT_TESTED, USABLE, NOT_USABLE }; /** * @brief Provides an abstraction layer to the hardware acceleration APIs in FFmpeg. */ class HardwareAccel { public: /** * @brief Transfers hardware frame to main memory. * * Transfers a hardware decoded frame back to main memory. Should be called after * the frame is decoded using avcodec_send_packet/avcodec_receive_frame. * * If @frame is software, this is a no-op. * * @param frame Refrerence to the decoded hardware frame. * @param desiredFormat Software pixel format that the hardware outputs. * @returns Software frame. */ static std::unique_ptr<VideoFrame> transferToMainMemory(const VideoFrame& frame, AVPixelFormat desiredFormat); /** * @brief Constructs a HardwareAccel object * * Made public so std::unique_ptr can access it. Should not be called. */ HardwareAccel(AVCodecID id, const std::string& name, AVHWDeviceType hwType, AVPixelFormat format, AVPixelFormat swFormat, CodecType type, bool dynBitrate); /** * @brief Dereferences hardware contexts. */ ~HardwareAccel(); /** * @brief Codec that is being accelerated. */ AVCodecID getCodecId() const { return id_; }; /** * @brief Name of the hardware layer/API being used. */ const std::string& getName() const { return name_; }; /** * @brief Hardware format. */ AVPixelFormat getFormat() const { return format_; }; /** * @brief Software format. * * For encoding it is the format expected by the hardware. For decoding * it is the format output by the hardware. */ AVPixelFormat getSoftwareFormat() const { return swFormat_; } /** * @brief Gets the name of the codec. * * Decoding: avcodec_get_name(id_) * Encoding: avcodec_get_name(id_) + '_' + name_ */ std::string getCodecName() const; /** * @brief If hardware decoder can feed hardware encoder directly. * * Returns whether or not the decoder is linked to an encoder or vice-versa. Being linked * means an encoder can directly use the decoder's hardware frame, without first * transferring it to main memory. */ bool isLinked() const { return linked_; } /** * @brief Set some extra details in the codec context. * * Should be called after a successful * setup (setupDecoder or setupEncoder). * For decoding, sets the hw_device_ctx and get_format callback. If the decoder has * a frames context, mark as linked. * For encoding, sets hw_device_ctx and hw_frames_ctx, and may set some hardware * codec options. */ void setDetails(AVCodecContext* codecCtx); /** * @brief Transfers a frame to/from the GPU memory. * * Transfers a hardware decoded frame back to main memory. Should be called after * the frame is decoded using avcodec_send_packet/avcodec_receive_frame or before * the frame is encoded using avcodec_send_frame/avcodec_receive_packet. * * @param frame Hardware frame when decoding, software frame when encoding. * @returns Software frame when decoding, hardware frame when encoding. */ std::unique_ptr<VideoFrame> transfer(const VideoFrame& frame); /** * @brief Links this HardwareAccel's frames context with the passed in context. * * This serves to skip transferring a decoded frame back to main memory before encoding. */ bool linkHardware(AVBufferRef* framesCtx); static std::list<HardwareAccel> getCompatibleAccel(AVCodecID id, int width, int height, CodecType type); int initAPI(bool linkable, AVBufferRef* framesCtx); bool dynBitrate() { return dynBitrate_; } private: bool initDevice(const std::string& device); bool initFrame(); AVCodecID id_ {AV_CODEC_ID_NONE}; std::string name_; AVHWDeviceType hwType_ {AV_HWDEVICE_TYPE_NONE}; AVPixelFormat format_ {AV_PIX_FMT_NONE}; AVPixelFormat swFormat_ {AV_PIX_FMT_NONE}; CodecType type_ {CODEC_NONE}; bool linked_ {false}; int width_ {0}; int height_ {0}; bool dynBitrate_ {false}; AVBufferRef* deviceCtx_ {nullptr}; AVBufferRef* framesCtx_ {nullptr}; int init_device(const char* name, const char* device, int flags); int init_device_type(std::string& dev); std::list<std::pair<std::string, DeviceState>>* possible_devices_; }; } // namespace video } // namespace jami
5,797
C++
.h
158
30.196203
93
0.655682
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,967
filter_transpose.h
savoirfairelinux_jami-daemon/src/media/video/filter_transpose.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 "../media_filter.h" namespace jami { namespace video { std::unique_ptr<MediaFilter> getTransposeFilter( int rotation, std::string inputName, int width, int height, int format, bool rescale); } } // namespace jami
960
C++
.h
24
38.041667
90
0.751073
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,968
video_device_monitor.h
savoirfairelinux_jami-daemon/src/media/video/video_device_monitor.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/>. */ #ifndef VIDEO_DEVICE_MONITOR_H__ #define VIDEO_DEVICE_MONITOR_H__ #include "config/serializable.h" #include "noncopyable.h" #include <map> #include <string> #include <memory> #include "video_device.h" namespace YAML { class Emitter; class Node; } // namespace YAML namespace jami { namespace video { class VideoDeviceMonitorImpl; class VideoDeviceMonitor : public Serializable { public: VideoDeviceMonitor(); ~VideoDeviceMonitor(); std::vector<std::string> getDeviceList() const; libjami::VideoCapabilities getCapabilities(const std::string& name) const; VideoSettings getSettings(const std::string& name); void applySettings(const std::string& name, const VideoSettings& settings); std::string getDefaultDevice() const; std::string getMRLForDefaultDevice() const; bool setDefaultDevice(const std::string& name); void setDeviceOrientation(const std::string& id, int angle); bool addDevice(const std::string& node, const std::vector<std::map<std::string, std::string>>& devInfo = {}); void removeDevice(const std::string& node); void removeDeviceViaInput(const std::string& path); /** * Params for libav */ DeviceParams getDeviceParams(const std::string& name) const; /* * Interface to load from/store to the (YAML) configuration file. */ void serialize(YAML::Emitter& out) const override; virtual void unserialize(const YAML::Node& in) override; private: NON_COPYABLE(VideoDeviceMonitor); mutable std::mutex lock_; /* * User preferred settings for a device, * as loaded from (and stored to) the configuration file. */ std::vector<VideoSettings> preferences_; void overwritePreferences(const VideoSettings& settings); std::vector<VideoSettings>::iterator findPreferencesById(const std::string& id); /* * Vector containing the video devices. */ std::vector<VideoDevice> devices_; std::string defaultDevice_ = ""; std::vector<VideoDevice>::iterator findDeviceById(const std::string& id); std::vector<VideoDevice>::const_iterator findDeviceById(const std::string& id) const; std::unique_ptr<VideoDeviceMonitorImpl> monitorImpl_; constexpr static const char* CONFIG_LABEL = "video"; }; } // namespace video } // namespace jami #endif /* VIDEO_DEVICE_MONITOR_H__ */
3,088
C++
.h
80
34.775
89
0.730653
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,969
video_device.h
savoirfairelinux_jami-daemon/src/media/video/video_device.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 "media/media_device.h" #include "video_base.h" #include "rational.h" #include "videomanager_interface.h" #include "string_utils.h" #include "logger.h" #include <fmt/core.h> #include <cmath> #include <map> #include <memory> #include <string> #include <vector> #include <algorithm> #include <sstream> namespace jami { namespace video { using VideoSize = std::pair<unsigned, unsigned>; using FrameRate = rational<double>; static constexpr const char DEVICE_DESKTOP[] = "desktop"; class VideoDeviceImpl; class VideoDevice { public: VideoDevice(const std::string& path, const std::vector<std::map<std::string, std::string>>& devInfo); ~VideoDevice(); /* * The device name, e.g. "Integrated Camera", * actually used as the identifier. */ std::string name {}; const std::string& getDeviceId() const { return id_; } /* * Get the 3 level deep tree of possible settings for the device. * The levels are channels, sizes, and rates. * * The result map for the "Integrated Camera" looks like this: * * {'Camera 1': {'1280x720': ['10'], * '320x240': ['30', '15'], * '352x288': ['30', '15'], * '424x240': ['30', '15'], * '640x360': ['30', '15'], * '640x480': ['30', '15'], * '800x448': ['15'], * '960x540': ['10']}} */ libjami::VideoCapabilities getCapabilities() const { libjami::VideoCapabilities cap; for (const auto& chan : getChannelList()) for (const auto& size : getSizeList(chan)) { std::string sz = fmt::format("{}x{}", size.first, size.second); auto rates = getRateList(chan, size); std::vector<std::string> rates_str {rates.size()}; std::transform(rates.begin(), rates.end(), rates_str.begin(), [](const FrameRate& r) { return jami::to_string(r.real()); }); cap[chan][sz] = std::move(rates_str); } return cap; } /* Default setting is found by using following rules: * - frame height <= 640 pixels * - frame rate >= 10 fps */ VideoSettings getDefaultSettings() const { auto settings = getSettings(); auto channels = getChannelList(); if (channels.empty()) return {}; settings.channel = getChannelList().front(); VideoSize max_size {0, 0}; FrameRate max_size_rate {0}; auto sizes = getSizeList(settings.channel); for (auto& s : sizes) { if (s.second > 640) continue; auto rates = getRateList(settings.channel, s); if (rates.empty()) continue; auto max_rate = *std::max_element(rates.begin(), rates.end()); if (max_rate < 10) continue; if (s.second > max_size.second || (s.second == max_size.second && s.first > max_size.first)) { max_size = s; max_size_rate = max_rate; } } if (max_size.second > 0) { settings.video_size = fmt::format("{}x{}", max_size.first, max_size.second); settings.framerate = jami::to_string(max_size_rate.real()); JAMI_WARN("Default video settings: %s, %s FPS", settings.video_size.c_str(), settings.framerate.c_str()); } return settings; } /* * Get the settings for the device. */ VideoSettings getSettings() const { auto params = getDeviceParams(); VideoSettings settings; settings.name = name.empty() ? params.name : name; settings.unique_id = params.unique_id; settings.input = params.input; settings.channel = params.channel_name; settings.video_size = sizeToString(params.width, params.height); settings.framerate = jami::to_string(params.framerate.real()); return settings; } /* * Setup the device with the preferences listed in the "settings" map. * The expected map should be similar to the result of getSettings(). * * If a key is missing, a valid default value is choosen. Thus, calling * this function with an empty map will reset the device to default. */ void applySettings(VideoSettings settings) { DeviceParams params {}; params.name = settings.name; params.input = settings.input; params.unique_id = settings.unique_id; params.channel_name = settings.channel; auto size = sizeFromString(settings.channel, settings.video_size); params.width = size.first; params.height = size.second; params.framerate = rateFromString(settings.channel, size, settings.framerate); setDeviceParams(params); } void setOrientation(int orientation) { orientation_ = orientation; } /** * Returns the parameters needed for actual use of the device */ DeviceParams getDeviceParams() const; std::vector<std::string> getChannelList() const; private: std::vector<VideoSize> getSizeList(const std::string& channel) const; std::vector<FrameRate> getRateList(const std::string& channel, VideoSize size) const; VideoSize sizeFromString(const std::string& channel, const std::string& size) const { auto size_list = getSizeList(channel); for (const auto& s : size_list) { if (sizeToString(s.first, s.second) == size) return s; } return {0, 0}; } std::string sizeToString(unsigned w, unsigned h) const { return fmt::format("{}x{}", w, h); } FrameRate rateFromString(const std::string& channel, VideoSize size, const std::string& rate) const { FrameRate closest {0}; double rate_val = 0; try { rate_val = rate.empty() ? 0 : jami::stod(rate); } catch (...) { JAMI_WARN("Unable to read framerate \"%s\"", rate.c_str()); } // fallback to framerate closest to 30 FPS if (rate_val == 0) rate_val = 30; double closest_dist = std::numeric_limits<double>::max(); auto rate_list = getRateList(channel, size); for (const auto& r : rate_list) { double dist = std::fabs(r.real() - rate_val); if (dist < closest_dist) { closest = r; closest_dist = dist; } } return closest; } void setDeviceParams(const DeviceParams&); /* * The device node, e.g. "046d082dF41A2B3F". */ std::string id_ {}; int orientation_ {0}; /* * Device specific implementation. * On Linux, V4L2 stuffs go there. * * Note: since a VideoDevice is copyable, * deviceImpl_ cannot be an unique_ptr. */ std::shared_ptr<VideoDeviceImpl> deviceImpl_; }; } // namespace video } // namespace jami
7,909
C++
.h
216
29
102
0.591935
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,970
capture_graph_interfaces.h
savoirfairelinux_jami-daemon/src/media/video/winvideo/capture_graph_interfaces.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/>. */ #ifndef CAPTURE_GRAPH_INTERFACES #define CAPTURE_GRAPH_INTERFACES #include <dshow.h> namespace jami { namespace video { class CaptureGraphInterfaces { public: CaptureGraphInterfaces() : captureGraph_(nullptr) , graph_(nullptr) , videoInputFilter_(nullptr) , streamConf_(nullptr) {} ICaptureGraphBuilder2* captureGraph_; IGraphBuilder* graph_; IBaseFilter* videoInputFilter_; IAMStreamConfig* streamConf_; }; } // namespace video } // namespace jami #endif
1,236
C++
.h
38
29.473684
73
0.739715
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,971
audio_rtp_session.h
savoirfairelinux_jami-daemon/src/media/audio/audio_rtp_session.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 "media/media_device.h" #include "media/rtp_session.h" #include "media/media_stream.h" #include "threadloop.h" #include <string> #include <memory> namespace jami { class AudioInput; class AudioReceiveThread; class AudioSender; class IceSocket; class MediaRecorder; class RingBuffer; struct RTCPInfo { float packetLoss; unsigned int jitter; unsigned int nb_sample; float latency; }; class AudioRtpSession : public RtpSession, public std::enable_shared_from_this<AudioRtpSession> { public: AudioRtpSession(const std::string& callId, const std::string& streamId, const std::shared_ptr<MediaRecorder>& rec); virtual ~AudioRtpSession(); void start(std::unique_ptr<dhtnet::IceSocket> rtp_sock, std::unique_ptr<dhtnet::IceSocket> rtcp_sock) override; void restartSender() override; void stop() override; void setMuted(bool muted, Direction dir = Direction::SEND) override; void initRecorder() override; void deinitRecorder() override; std::shared_ptr<AudioInput>& getAudioLocal() { return audioInput_; } std::unique_ptr<AudioReceiveThread>& getAudioReceive() { return receiveThread_; } void setVoiceCallback(std::function<void(bool)> cb); private: void startSender(); void startReceiver(); bool check_RCTP_Info_RR(RTCPInfo& rtcpi); void adaptQualityAndBitrate(); void dropProcessing(RTCPInfo* rtcpi); void setNewPacketLoss(unsigned int newPL); float getPonderateLoss(float lastLoss); std::unique_ptr<AudioSender> sender_; std::unique_ptr<AudioReceiveThread> receiveThread_; std::shared_ptr<AudioInput> audioInput_; std::shared_ptr<RingBuffer> ringbuffer_; uint16_t initSeqVal_ {0}; bool muteState_ {false}; unsigned packetLoss_ {10}; DeviceParams localAudioParams_; InterruptedThreadLoop rtcpCheckerThread_; void processRtcpChecker(); // Interval in seconds between RTCP checking std::chrono::seconds rtcp_checking_interval {4}; std::function<void(bool)> voiceCallback_; void attachRemoteRecorder(const MediaStream& ms); void attachLocalRecorder(const MediaStream& ms); }; } // namespace jami
2,930
C++
.h
78
33.730769
115
0.742414
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,972
audioloop.h
savoirfairelinux_jami-daemon/src/media/audio/audioloop.h
/* * 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/>. */ #pragma once #include "ring_types.h" #include "noncopyable.h" #include "audio_format.h" #include "media_buffer.h" extern "C" { #include <libavutil/frame.h> } /** * @file audioloop.h * @brief Loop on a sound file */ namespace jami { class AudioLoop { public: AudioLoop(AudioFormat format); AudioLoop& operator=(AudioLoop&& o) noexcept { std::swap(buffer_, o.buffer_); std::swap(pos_, o.pos_); return *this; } virtual ~AudioLoop(); /** * Get the next fragment of the tone * the function change the intern position, and will loop * @param output The data buffer * @param nb of int16 to send * @param gain The gain [-1.0, 1.0] */ void getNext(AVFrame* output, bool mute); std::unique_ptr<AudioFrame> getNext(size_t samples = 0, bool mute = false); void seek(double relative_position); /** * Reset the pointer position */ void reset() { pos_ = 0; } /** * Accessor to the size of the buffer * @return unsigned int The size */ size_t getSize() const { return buffer_->nb_samples; } AudioFormat getFormat() const { return format_; } protected: AudioFormat format_; /** The data buffer */ libjami::FrameBuffer buffer_ {}; /** current position, set to 0, when initialize */ size_t pos_ {0}; private: NON_COPYABLE(AudioLoop); virtual void onBufferFinish(); }; } // namespace jami
2,267
C++
.h
74
26.945946
79
0.682277
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,973
tonecontrol.h
savoirfairelinux_jami-daemon/src/media/audio/tonecontrol.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 "preferences.h" #include "audio/sound/tone.h" // for Tone::TONEID declaration #include "audio/sound/audiofile.h" #include <mutex> namespace jami { /** * ToneControl is a class to handle application wide business logic * to control audio tones played at various application events. * Having an application wide instance gives a way to handle * complexes interactions occurring in a multi-call context. */ class TelephoneTone; class ToneControl { public: ToneControl() = delete; ToneControl(const Preferences& preferences); ~ToneControl(); void setSampleRate(unsigned rate, AVSampleFormat sampleFormat); std::shared_ptr<AudioLoop> getTelephoneTone(); std::shared_ptr<AudioLoop> getTelephoneFile(void); bool setAudioFile(const std::string& file); void stopAudioFile(); void stop(); void play(Tone::ToneId toneId); void seek(double value); private: const Preferences& prefs_; std::mutex mutex_; // protect access to following members unsigned sampleRate_; AVSampleFormat sampleFormat_; std::unique_ptr<TelephoneTone> telephoneTone_; std::shared_ptr<AudioFile> audioFile_; }; } // namespace jami
1,913
C++
.h
52
33.903846
73
0.752026
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,974
audio_receive_thread.h
savoirfairelinux_jami-daemon/src/media/audio/audio_receive_thread.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 "audio_format.h" #include "media/media_buffer.h" #include "media/media_device.h" #include "media/media_codec.h" #include "noncopyable.h" #include "observer.h" #include "media/socket_pair.h" #include "threadloop.h" #include <functional> #include <sstream> namespace jami { class MediaDecoder; class MediaIOHandle; struct MediaStream; class RingBuffer; class AudioReceiveThread : public Observable<std::shared_ptr<MediaFrame>> { public: AudioReceiveThread(const std::string& streamId, const AudioFormat& format, const std::string& sdp, const uint16_t mtu); ~AudioReceiveThread(); MediaStream getInfo() const; void addIOContext(SocketPair& socketPair); void startReceiver(); void stopReceiver(); void setSuccessfulSetupCb(const std::function<void(MediaType, bool)>& cb) { onSuccessfulSetup_ = cb; } void setRecorderCallback(const std::function<void(const MediaStream& ms)>& cb); private: NON_COPYABLE(AudioReceiveThread); static constexpr auto SDP_FILENAME = "dummyFilename"; static int interruptCb(void* ctx); static int readFunction(void* opaque, uint8_t* buf, int buf_size); /*-----------------------------------------------------------------*/ /* These variables should be used in thread (i.e. process()) only! */ /*-----------------------------------------------------------------*/ const std::string streamId_; const AudioFormat& format_; DeviceParams args_; std::istringstream stream_; mutable std::mutex mutex_; std::unique_ptr<MediaDecoder> audioDecoder_; std::unique_ptr<MediaIOHandle> sdpContext_; std::unique_ptr<MediaIOHandle> demuxContext_; std::shared_ptr<RingBuffer> ringbuffer_; uint16_t mtu_; ThreadLoop loop_; bool setup(); void process(); void cleanup(); std::function<void(MediaType, bool)> onSuccessfulSetup_; std::function<void(const MediaStream& ms)> recorderCallback_; }; } // namespace jami
2,782
C++
.h
75
32.84
83
0.681057
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,975
ringbuffer.h
savoirfairelinux_jami-daemon/src/media/audio/ringbuffer.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 "audio_format.h" #include "noncopyable.h" #include "audio_frame_resizer.h" #include "resampler.h" #include <atomic> #include <condition_variable> #include <mutex> #include <chrono> #include <map> #include <vector> #include <fstream> namespace jami { /** * A ring buffer for mutichannel audio samples */ class RingBuffer { public: using clock = std::chrono::high_resolution_clock; using time_point = clock::time_point; using FrameCallback = std::function<void(const std::shared_ptr<AudioFrame>&)>; /** * Constructor * @param size Size of the buffer to create */ RingBuffer(const std::string& id, size_t size, AudioFormat format = AudioFormat::MONO()); /** * Destructor */ ~RingBuffer(); const std::string& getId() const { return id; } /** * Reset the counters to 0 for this read offset */ void flush(const std::string& ringbufferId); void flushAll(); inline AudioFormat getFormat() const { return format_; } inline void setFormat(const AudioFormat& format) { std::lock_guard l(writeLock_); format_ = format; resizer_.setFormat(format, format.sample_rate / 50); } /** * Add a new readoffset for this ringbuffer */ void createReadOffset(const std::string& ringbufferId); void createReadOffset(const std::string& ringbufferId, FrameCallback cb); /** * Remove a readoffset for this ringbuffer */ void removeReadOffset(const std::string& ringbufferId); size_t readOffsetCount() const { return readoffsets_.size(); } /** * Write data in the ring buffer * @param AudioFrame */ void put(std::shared_ptr<AudioFrame>&& data); /** * To get how much samples are available in the buffer to read in * @return int The available (multichannel) samples number */ size_t availableForGet(const std::string& ringbufferId) const; /** * Get data in the ring buffer * @param ringbufferId * @return AudioFRame */ std::shared_ptr<AudioFrame> get(const std::string& ringbufferId); /** * Discard data from the buffer * @param toDiscard Number of samples to discard * @return size_t Number of samples discarded */ size_t discard(size_t toDiscard, const std::string& ringbufferId); /** * Total length of the ring buffer which is available for "putting" * @return int */ size_t putLength() const; size_t getLength(const std::string& ringbufferId) const; inline bool isFull() const { return putLength() == buffer_.size(); } inline bool isEmpty() const { return putLength() == 0; } inline void setFrameSize(int nb_samples) { resizer_.setFrameSize(nb_samples); } /** * Blocks until min_data_length samples of data is available, or until deadline has passed. * * @param ringbufferId The read offset for which data should be available. * @param min_data_length Minimum number of samples that should be available for the call to return * @param deadline The ringbufferId is guaranteed to end after this time point. If no deadline is provided, * the call blocks indefinitely. * @return available data for ringbufferId after the call returned (same as calling getLength(ringbufferId) ). */ size_t waitForDataAvailable(const std::string& ringbufferId, const time_point& deadline = time_point::max()) const; /** * Debug function print mEnd, mStart, mBufferSize */ void debug(); bool isAudioMeterActive() const { return rmsSignal_; } void setAudioMeterState(bool state) { rmsSignal_ = state; } private: struct ReadOffset { size_t offset; FrameCallback callback; }; using ReadOffsetMap = std::map<std::string, ReadOffset>; NON_COPYABLE(RingBuffer); void putToBuffer(std::shared_ptr<AudioFrame>&& data); bool hasNoReadOffsets() const; /** * Return the smalest readoffset. Useful to evaluate if ringbuffer is full */ size_t getSmallestReadOffset() const; /** * Get read offset coresponding to this call */ size_t getReadOffset(const std::string& ringbufferId) const; /** * Move readoffset forward by offset */ void storeReadOffset(size_t offset, const std::string& ringbufferId); /** * Test if readoffset coresponding to this call is still active */ bool hasThisReadOffset(const std::string& ringbufferId) const; /** * Discard data from all read offsets to make place for new data. */ size_t discard(size_t toDiscard); const std::string id; /** Offset on the last data */ size_t endPos_; /** Data */ AudioFormat format_ {AudioFormat::DEFAULT()}; std::vector<std::shared_ptr<AudioFrame>> buffer_ {16}; mutable std::mutex lock_; mutable std::condition_variable not_empty_; std::mutex writeLock_; ReadOffsetMap readoffsets_; Resampler resampler_; AudioFrameResizer resizer_; std::atomic_bool rmsSignal_ {false}; double rmsLevel_ {0}; int rmsFrameCount_ {0}; }; } // namespace jami
5,922
C++
.h
165
30.866667
114
0.685159
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,976
audio_frame_resizer.h
savoirfairelinux_jami-daemon/src/media/audio/audio_frame_resizer.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 "audio_format.h" #include "media/media_buffer.h" #include "noncopyable.h" #include <mutex> extern "C" { struct AVAudioFifo; } namespace jami { /** * Buffers extra samples. This is in case an input's frame size (number of samples in * a frame) and the output's frame size don't match. The queue will store the extra * samples until a frame can be read. Will call passed in callback once a frame is output. * * Works at frame-level instead of sample- or byte-level like FFmpeg's FIFO buffers. */ class AudioFrameResizer { public: AudioFrameResizer(const AudioFormat& format, int frameSize, std::function<void(std::shared_ptr<AudioFrame>&&)> cb = {}); ~AudioFrameResizer(); /** * Gets the numbers of samples available for reading. */ int samples() const; /** * Gets the format used by @queue_, input frames must match this format or enqueuing * will fail. Returned frames are in this format. */ AudioFormat format() const; void setFormat(const AudioFormat& format, int frameSize); void setFrameSize(int frameSize); /** * Gets the number of samples per output frame. */ int frameSize() const; /** * Write @frame's data to the queue. The internal buffer will be reallocated if * there's not enough space for @frame's samples. * * Returns the number of samples written, or negative on error. * * NOTE @frame's format must match @format_, or this will fail. */ void enqueue(std::shared_ptr<AudioFrame>&& frame); /** * Notifies owner of a new frame. */ std::shared_ptr<AudioFrame> dequeue(); private: NON_COPYABLE(AudioFrameResizer); /** * Format used for input and output audio frames. */ AudioFormat format_; /** * Number of samples in each output frame. */ int frameSize_; /** * Function to call once @queue_ contains enough samples to produce a frame. */ std::function<void(std::shared_ptr<AudioFrame>&&)> cb_; /** * Audio queue operating on the sample level instead of byte level. */ AVAudioFifo* queue_; int64_t nextOutputPts_ {0}; bool hasVoice_ {false}; }; } // namespace jami
3,003
C++
.h
89
29.348315
90
0.684501
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,977
audiolayer.h
savoirfairelinux_jami-daemon/src/media/audio/audiolayer.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 "ringbuffer.h" #include "noncopyable.h" #include "audio_frame_resizer.h" #include "audio-processing/audio_processor.h" #include <chrono> #include <mutex> #include <vector> #include <atomic> #include <condition_variable> #include <array> extern "C" { struct SpeexEchoState_; typedef struct SpeexEchoState_ SpeexEchoState; } /** * @file audiolayer.h * @brief Main sound class. Manages the data transfers between the application and the hardware. */ // Define the audio api #define OPENSL_API_STR "opensl" #define PULSEAUDIO_API_STR "pulseaudio" #define ALSA_API_STR "alsa" #define JACK_API_STR "jack" #define COREAUDIO_API_STR "coreaudio" #define PORTAUDIO_API_STR "portaudio" #define PCM_DEFAULT "default" // Default ALSA plugin #define PCM_DSNOOP "plug:dsnoop" // Alsa plugin for microphone sharing #define PCM_DMIX_DSNOOP "dmix/dsnoop" // Audio profile using Alsa dmix/dsnoop namespace jami { class AudioPreference; class Resampler; enum class AudioDeviceType { ALL = -1, PLAYBACK = 0, CAPTURE, RINGTONE }; class AudioLayer { private: NON_COPYABLE(AudioLayer); protected: enum class Status { Idle, Starting, Started }; public: AudioLayer(const AudioPreference&); virtual ~AudioLayer(); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold */ virtual void startStream(AudioDeviceType stream = AudioDeviceType::ALL) = 0; /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state */ virtual void stopStream(AudioDeviceType stream = AudioDeviceType::ALL) = 0; virtual std::vector<std::string> getCaptureDeviceList() const = 0; virtual std::vector<std::string> getPlaybackDeviceList() const = 0; virtual int getAudioDeviceIndex(const std::string& name, AudioDeviceType type) const = 0; virtual std::string getAudioDeviceName(int index, AudioDeviceType type) const = 0; virtual int getIndexCapture() const = 0; virtual int getIndexPlayback() const = 0; virtual int getIndexRingtone() const = 0; /** * Determine whether or not the audio layer is active (i.e. playback opened) */ inline bool isStarted() const { return status_ == Status::Started; } template<class Rep, class Period> bool waitForStart(const std::chrono::duration<Rep, Period>& rel_time) const { std::unique_lock lk(mutex_); startedCv_.wait_for(lk, rel_time, [this] { return isStarted(); }); return isStarted(); } /** * Send a chunk of data to the hardware buffer to start the playback * Copy data in the urgent buffer. * @param buffer The buffer containing the data to be played ( ringtones ) */ void putUrgent(std::shared_ptr<AudioFrame> buffer); /** * Start/Stop playing the incoming call notification sound (beep) * while playing back audio (typically during an ongoing call). */ void playIncomingCallNotification(bool play) { playIncomingCallBeep_.exchange(play); } /** * Flush main buffer */ void flushMain(); /** * Flush urgent buffer */ void flushUrgent(); bool isCaptureMuted() const { return isCaptureMuted_; } /** * Mute capture (microphone) */ void muteCapture(bool muted) { isCaptureMuted_ = muted; } bool isPlaybackMuted() const { return isPlaybackMuted_; } /** * Mute playback */ void mutePlayback(bool muted) { isPlaybackMuted_ = muted; } bool isRingtoneMuted() const { return isRingtoneMuted_; } void muteRingtone(bool muted) { isRingtoneMuted_ = muted; } /** * Set capture stream gain (microphone) * Range should be [-1.0, 1.0] */ void setCaptureGain(double gain) { captureGain_ = gain; } /** * Get capture stream gain (microphone) */ double getCaptureGain() const { return captureGain_; } /** * Set playback stream gain (speaker) * Range should be [-1.0, 1.0] */ void setPlaybackGain(double gain) { playbackGain_ = gain; } /** * Get playback stream gain (speaker) */ double getPlaybackGain() const { return playbackGain_; } /** * Get the sample rate of the audio layer * @return unsigned int The sample rate * default: 44100 HZ */ unsigned int getSampleRate() const { return audioFormat_.sample_rate; } /** * Get the audio format of the layer (sample rate & channel number). */ AudioFormat getFormat() const { return audioFormat_; } /** * Emit an audio notification (beep) on incoming calls */ void notifyIncomingCall(); virtual void updatePreference(AudioPreference& pref, int index, AudioDeviceType type) = 0; protected: /** * Callback to be called by derived classes when the audio output is opened. */ void hardwareFormatAvailable(AudioFormat playback, size_t bufSize = 0); /** * Set the input format on necessary objects. */ void hardwareInputFormatAvailable(AudioFormat capture); void devicesChanged(); void playbackChanged(bool started); void recordChanged(bool started); void setHasNativeAEC(bool hasEAC); void setHasNativeNS(bool hasNS); std::shared_ptr<AudioFrame> getToPlay(AudioFormat format, size_t writableSamples); std::shared_ptr<AudioFrame> getToRing(AudioFormat format, size_t writableSamples); std::shared_ptr<AudioFrame> getPlayback(AudioFormat format, size_t samples) { const auto& ringBuff = getToRing(format, samples); const auto& playBuff = getToPlay(format, samples); return ringBuff ? ringBuff : playBuff; } void putRecorded(std::shared_ptr<AudioFrame>&& frame); void flush(); /** * True if capture is not to be used */ bool isCaptureMuted_; /** * True if playback is not to be used */ bool isPlaybackMuted_; /** * True if ringtone should be muted */ bool isRingtoneMuted_ {false}; bool playbackStarted_ {false}; bool recordStarted_ {false}; bool hasNativeAEC_ {true}; bool hasNativeNS_ {false}; /** * Gain applied to mic signal */ double captureGain_; /** * Gain applied to playback signal */ double playbackGain_; // audio processor preferences const AudioPreference& pref_; /** * Buffers for audio processing */ std::shared_ptr<RingBuffer> mainRingBuffer_; std::unique_ptr<AudioFrameResizer> playbackQueue_; /** * Whether or not the audio layer's playback stream is started */ std::atomic<Status> status_ {Status::Idle}; mutable std::condition_variable startedCv_; /** * Sample Rate that should be sent to the sound card */ AudioFormat audioFormat_; /** * Sample Rate for input. */ AudioFormat audioInputFormat_; size_t nativeFrameSize_ {0}; /** * Urgent ring buffer used for ringtones */ RingBuffer urgentRingBuffer_; /** * Lock for the entire audio layer */ mutable std::mutex mutex_ {}; /** * Manage sampling rate conversion */ std::unique_ptr<Resampler> resampler_; private: std::mutex audioProcessorMutex {}; std::unique_ptr<AudioProcessor> audioProcessor; void createAudioProcessor(); void destroyAudioProcessor(); // Set to "true" to play the incoming call notification (beep) // when the playback is on (typically when there is already an // active call). std::atomic_bool playIncomingCallBeep_ {false}; /** * Time of the last incoming call notification */ std::chrono::system_clock::time_point lastNotificationTime_ { std::chrono::system_clock::time_point::min()}; }; } // namespace jami
8,634
C++
.h
247
30.174089
96
0.688086
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,978
audio_sender.h
savoirfairelinux_jami-daemon/src/media/audio/audio_sender.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 "media_buffer.h" #include "media_codec.h" #include "noncopyable.h" #include "observer.h" #include "socket_pair.h" namespace jami { class AudioInput; class MediaEncoder; class MediaIOHandle; class Resampler; class AudioSender : public Observer<std::shared_ptr<MediaFrame>> { public: AudioSender(const std::string& dest, const MediaDescription& args, SocketPair& socketPair, const uint16_t seqVal, const uint16_t mtu); ~AudioSender(); uint16_t getLastSeqValue(); int setPacketLoss(uint64_t pl); void setVoiceCallback(std::function<void(bool)> cb); void update(Observable<std::shared_ptr<jami::MediaFrame>>*, const std::shared_ptr<jami::MediaFrame>&) override; private: NON_COPYABLE(AudioSender); bool setup(SocketPair& socketPair); std::string dest_; MediaDescription args_; std::unique_ptr<MediaEncoder> audioEncoder_; std::unique_ptr<MediaIOHandle> muxContext_; uint64_t sent_samples = 0; const uint16_t seqVal_; uint16_t mtu_; // last voice activity state bool voice_ {false}; std::function<void(bool)> voiceCallback_; }; } // namespace jami
1,948
C++
.h
56
30.553571
73
0.713525
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,979
audio_format.h
savoirfairelinux_jami-daemon/src/media/audio/audio_format.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 extern "C" { #include <libavutil/samplefmt.h> } #include <fmt/core.h> #include <sstream> #include <string> #include <cstddef> // for size_t namespace jami { /** * Structure to hold sample rate and channel number associated with audio data. */ struct AudioFormat { unsigned sample_rate; unsigned nb_channels; AVSampleFormat sampleFormat; constexpr AudioFormat(unsigned sr, unsigned c, AVSampleFormat f = AV_SAMPLE_FMT_S16) : sample_rate(sr) , nb_channels(c) , sampleFormat(f) {} inline bool operator==(const AudioFormat& b) const { return ((b.sample_rate == sample_rate) && (b.nb_channels == nb_channels) && (b.sampleFormat == sampleFormat)); } inline bool operator!=(const AudioFormat& b) const { return !(*this == b); } inline std::string toString() const { return fmt::format("{{{}, {} channels, {}Hz}}", av_get_sample_fmt_name(sampleFormat), nb_channels, sample_rate); } inline AudioFormat withSampleFormat(AVSampleFormat format) { return {sample_rate, nb_channels, format}; } /** * Returns bytes necessary to hold one frame of audio data. */ inline size_t getBytesPerFrame() const { return av_get_bytes_per_sample(sampleFormat) * nb_channels; } /** * Bytes per second (default), or bytes necessary * to hold delay_ms milliseconds of audio data. */ inline size_t getBandwidth(unsigned delay_ms = 1000) const { return (getBytesPerFrame() * sample_rate * delay_ms) / 1000; } static const constexpr unsigned DEFAULT_SAMPLE_RATE = 48000; static const constexpr AudioFormat DEFAULT() { return AudioFormat {16000, 1}; } static const constexpr AudioFormat NONE() { return AudioFormat {0, 0}; } static const constexpr AudioFormat MONO() { return AudioFormat {DEFAULT_SAMPLE_RATE, 1}; } static const constexpr AudioFormat STEREO() { return AudioFormat {DEFAULT_SAMPLE_RATE, 2}; } }; } // namespace jami
2,744
C++
.h
71
34.380282
120
0.696126
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,980
audio_input.h
savoirfairelinux_jami-daemon/src/media/audio/audio_input.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 <atomic> #include <future> #include <mutex> #include <chrono> #include "audio_format.h" #include "media/media_device.h" #include "media/media_buffer.h" #include "observer.h" #include "threadloop.h" #include "media/media_codec.h" namespace jami { class AudioDeviceGuard; class AudioFrameResizer; class MediaDemuxer; class MediaDecoder; class MediaRecorder; struct MediaStream; class Resampler; class RingBuffer; class AudioInput : public Observable<std::shared_ptr<MediaFrame>> { public: AudioInput(const std::string& id); AudioInput(const std::string& id, const std::string& resource); ~AudioInput(); std::shared_future<DeviceParams> switchInput(const std::string& resource); void start() { loop_.start(); }; bool isCapturing() const { return loop_.isRunning(); } void setFormat(const AudioFormat& fmt); void setMuted(bool isMuted); MediaStream getInfo() const; MediaStream getInfo(const std::string& name) const; void updateStartTime(int64_t start); void setPaused(bool paused); void configureFilePlayback(const std::string& path, std::shared_ptr<MediaDemuxer>& demuxer, int index); void flushBuffers(); void setSeekTime(int64_t time); void setSuccessfulSetupCb(const std::function<void(MediaType, bool)>& cb) { onSuccessfulSetup_ = cb; } void setRecorderCallback(const std::function<void(const MediaStream& ms)>& cb); std::string getId() const { return id_; }; private: void readFromDevice(); void readFromFile(); void readFromQueue(); bool initDevice(const std::string& device); bool initFile(const std::string& path); bool createDecoder(); void frameResized(std::shared_ptr<AudioFrame>&& ptr); std::string id_; std::shared_ptr<RingBuffer> ringBuf_; bool muteState_ {false}; uint64_t sent_samples = 0; mutable std::mutex fmtMutex_ {}; AudioFormat format_; int frameSize_; std::atomic_bool paused_ {true}; std::unique_ptr<Resampler> resampler_; std::unique_ptr<AudioFrameResizer> resizer_; std::unique_ptr<MediaDecoder> decoder_; std::string resource_; std::mutex resourceMutex_ {}; DeviceParams devOpts_; std::promise<DeviceParams> foundDevOpts_; std::shared_future<DeviceParams> futureDevOpts_; std::atomic_bool devOptsFound_ {false}; void foundDevOpts(const DeviceParams& params); std::atomic_bool playingDevice_ {false}; std::atomic_bool decodingFile_ {false}; std::atomic_bool playingFile_ {false}; std::unique_ptr<AudioDeviceGuard> deviceGuard_; ThreadLoop loop_; void process(); std::chrono::time_point<std::chrono::steady_clock> wakeUp_; std::function<void(MediaType, bool)> onSuccessfulSetup_; std::function<void(const MediaStream& ms)> recorderCallback_; std::atomic_bool settingMS_ {true}; }; } // namespace jami
3,673
C++
.h
100
32.5
83
0.716174
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,981
ringbufferpool.h
savoirfairelinux_jami-daemon/src/media/audio/ringbufferpool.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 "audio_format.h" #include "media_buffer.h" #include "noncopyable.h" #include <map> #include <set> #include <string> #include <mutex> #include <memory> namespace jami { class RingBuffer; class RingBufferPool { public: static const char* const DEFAULT_ID; RingBufferPool(); ~RingBufferPool(); int getInternalSamplingRate() const { return internalAudioFormat_.sample_rate; } AudioFormat getInternalAudioFormat() const { return internalAudioFormat_; } void setInternalSamplingRate(unsigned sr); void setInternalAudioFormat(AudioFormat format); /** * Bind together two audio streams */ void bindRingbuffers(const std::string& ringbufferId1, const std::string& ringbufferId2); /** * Add a new ringbufferId to unidirectional outgoing stream * \param ringbufferId New ringbufferId to be added for this stream * \param processId Process that require this stream */ void bindHalfDuplexOut(const std::string& processId, const std::string& ringbufferId); /** * Unbind two ringbuffers */ void unbindRingbuffers(const std::string& ringbufferId1, const std::string& ringbufferId2); /** * Unbind a unidirectional stream */ void unBindHalfDuplexOut(const std::string& process_id, const std::string& ringbufferId); void unBindAllHalfDuplexOut(const std::string& ringbufferId); void unBindAll(const std::string& ringbufferId); bool waitForDataAvailable(const std::string& ringbufferId, const std::chrono::microseconds& max_wait) const; std::shared_ptr<AudioFrame> getData(const std::string& ringbufferId); std::shared_ptr<AudioFrame> getAvailableData(const std::string& ringbufferId); size_t availableForGet(const std::string& ringbufferId) const; size_t discard(size_t toDiscard, const std::string& ringbufferId); void flush(const std::string& ringbufferId); void flushAllBuffers(); /** * Create a new ringbuffer with a default readoffset. * This class keeps a weak reference on returned pointer, * so the caller is responsible of the referred instance. */ std::shared_ptr<RingBuffer> createRingBuffer(const std::string& id); /** * Obtain a shared pointer on a RingBuffer given by its ID. * If the ID doesn't match to any RingBuffer, the shared pointer * is empty. This non-const version flushes internal weak pointers * if the ID was used and the associated RingBuffer has been deleted. */ std::shared_ptr<RingBuffer> getRingBuffer(const std::string& id); /** * Works as non-const getRingBuffer, without the weak reference flush. */ std::shared_ptr<RingBuffer> getRingBuffer(const std::string& id) const; bool isAudioMeterActive(const std::string& id); void setAudioMeterState(const std::string& id, bool state); private: NON_COPYABLE(RingBufferPool); // A set of RingBuffers readable by a call using ReadBindings = std::set<std::shared_ptr<RingBuffer>, std::owner_less<std::shared_ptr<RingBuffer>>>; const ReadBindings* getReadBindings(const std::string& ringbufferId) const; ReadBindings* getReadBindings(const std::string& ringbufferId); void removeReadBindings(const std::string& ringbufferId); void addReaderToRingBuffer(const std::shared_ptr<RingBuffer>& rbuf, const std::string& ringbufferId); void removeReaderFromRingBuffer(const std::shared_ptr<RingBuffer>& rbuf, const std::string& ringbufferId); // A cache of created RingBuffers listed by IDs. std::map<std::string, std::weak_ptr<RingBuffer>> ringBufferMap_ {}; // A map of which RingBuffers a call has some ReadOffsets std::map<std::string, ReadBindings> readBindingsMap_ {}; mutable std::recursive_mutex stateLock_ {}; AudioFormat internalAudioFormat_ {AudioFormat::DEFAULT()}; std::shared_ptr<RingBuffer> defaultRingBuffer_; }; } // namespace jami
4,742
C++
.h
104
40.548077
105
0.727984
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,982
resampler.h
savoirfairelinux_jami-daemon/src/media/audio/resampler.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 "audio_format.h" #include "media/media_buffer.h" #include "noncopyable.h" extern "C" { struct AVFrame; struct SwrContext; } namespace jami { class AudioBuffer; /** * @brief Wrapper class for libswresample */ class Resampler { public: Resampler(); ~Resampler(); /** * @brief Resample a frame. * * Resample from @input format to @output format. * * NOTE: sample_rate, ch_layout, and format should be set on @output */ int resample(const AVFrame* input, AVFrame* output); /** * @brief Wrapper around resample(AVFrame*, AVFrame*) for convenience. */ std::unique_ptr<AudioFrame> resample(std::unique_ptr<AudioFrame>&& in, const AudioFormat& out); /** * @brief Wrapper around resample(AVFrame*, AVFrame*) for convenience. */ std::shared_ptr<AudioFrame> resample(std::shared_ptr<AudioFrame>&& in, const AudioFormat& out); private: NON_COPYABLE(Resampler); /** * @brief Reinitializes filter according to new format. * * Reinitializes the resampler when new settings are detected. As long as both input and * output formats don't change, this will only be called once. */ void reinit(const AVFrame* in, const AVFrame* out); /** * @brief Libswresample resampler context. * * NOTE SwrContext is an incomplete type and is unable to be stored in a smart pointer. */ SwrContext* swrCtx_; /** * @brief Number of times @swrCtx_ has been initialized with no successful audio resampling. * * 0: Uninitialized * 1: Initialized * >1: Invalid frames or formats, reinit is going to be called in an infinite loop */ unsigned initCount_; }; } // namespace jami
2,476
C++
.h
75
29.146667
99
0.69933
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,983
jacklayer.h
savoirfairelinux_jami-daemon/src/media/audio/jack/jacklayer.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 "noncopyable.h" #include "audio/audiolayer.h" #include <jack/jack.h> #include <jack/ringbuffer.h> #include <thread> #include <mutex> #include <vector> #include <condition_variable> #include <memory> namespace jami { class RingBuffer; class JackLayer : public AudioLayer { private: NON_COPYABLE(JackLayer); jack_client_t* captureClient_; jack_client_t* playbackClient_; std::vector<jack_port_t*> out_ports_; std::vector<jack_port_t*> in_ports_; std::vector<jack_ringbuffer_t*> out_ringbuffers_; std::vector<jack_ringbuffer_t*> in_ringbuffers_; std::thread ringbuffer_thread_; std::mutex ringbuffer_thread_mutex_; std::condition_variable data_ready_; static int process_capture(jack_nframes_t frames, void* arg); static int process_playback(jack_nframes_t frames, void* arg); void ringbuffer_worker(); void playback(); void capture(); std::unique_ptr<AudioFrame> read(); void write(const AudioFrame& buffer); size_t writeSpace(); std::vector<std::string> getCaptureDeviceList() const; std::vector<std::string> getPlaybackDeviceList() const; int getAudioDeviceIndex(const std::string& name, AudioDeviceType type) const; std::string getAudioDeviceName(int index, AudioDeviceType type) const; int getIndexCapture() const; int getIndexPlayback() const; int getIndexRingtone() const; void updatePreference(AudioPreference& pref, int index, AudioDeviceType type); /** * Start the capture and playback. */ void startStream(AudioDeviceType stream = AudioDeviceType::ALL); /** * Stop playback and capture. */ void stopStream(AudioDeviceType stream = AudioDeviceType::ALL); static void onShutdown(void* data); public: JackLayer(const AudioPreference&); ~JackLayer(); }; } // namespace jami
2,585
C++
.h
71
32.830986
82
0.732586
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,984
buf_manager.h
savoirfairelinux_jami-daemon/src/media/audio/opensl/buf_manager.h
/* * 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. */ #pragma once #include "logger.h" #include "noncopyable.h" #include <SLES/OpenSLES.h> #include <sys/types.h> #include <atomic> #include <cassert> #include <memory> #include <limits> #include <vector> /* * ProducerConsumerQueue, borrowed from Ian NiLewis */ template<typename T> class ProducerConsumerQueue { public: explicit ProducerConsumerQueue(size_t size) : buffer_(size) { // This is necessary because we depend on twos-complement wraparound // to take care of overflow conditions. assert(size < std::numeric_limits<int>::max()); } void clear() { read_.store(0); write_.store(0); } bool push(const T& item) { return push([&](T* ptr) -> bool { *ptr = item; return true; }); } // get() is idempotent between calls to commit(). T* getWriteablePtr() { T* result = nullptr; bool check __attribute__((unused)); //= false; check = push([&](T* head) -> bool { result = head; return false; // don't increment }); // if there's no space, result should not have been set, and vice versa assert(check == (result != nullptr)); return result; } bool commitWriteablePtr(T* ptr) { bool result = push([&](T* head) -> bool { // this writer func does nothing, because we assume that the caller // has already written to *ptr after acquiring it from a call to get(). // So just double-check that ptr is actually at the write head, and // return true to indicate that it's safe to advance. // if this isn't the same pointer we got from a call to get(), then // something has gone terribly wrong. Either there was an intervening // call to push() or commit(), or the pointer is spurious. assert(ptr == head); return true; }); return result; } // writer() can return false, which indicates that the caller // of push() changed its mind while writing (e.g. ran out of bytes) template<typename F> bool push(const F& writer) { bool result = false; int readptr = read_.load(std::memory_order_acquire); int writeptr = write_.load(std::memory_order_relaxed); // note that while readptr and writeptr will eventually // wrap around, taking their difference is still valid as // long as size_ < MAXINT. int space = buffer_.size() - (int) (writeptr - readptr); if (space >= 1) { result = true; // writer if (writer(buffer_.data() + (writeptr % buffer_.size()))) { ++writeptr; write_.store(writeptr, std::memory_order_release); } } return result; } // front out the queue, but not pop-out bool front(T* out_item) { return front([&](T* ptr) -> bool { *out_item = *ptr; return true; }); } void pop(void) { int readptr = read_.load(std::memory_order_relaxed); ++readptr; read_.store(readptr, std::memory_order_release); } template<typename F> bool front(const F& reader) { bool result = false; int writeptr = write_.load(std::memory_order_acquire); int readptr = read_.load(std::memory_order_relaxed); // As above, wraparound is ok int available = (int) (writeptr - readptr); if (available >= 1) { result = true; reader(buffer_.data() + (readptr % buffer_.size())); } return result; } uint32_t size(void) { int writeptr = write_.load(std::memory_order_acquire); int readptr = read_.load(std::memory_order_relaxed); return (uint32_t) (writeptr - readptr); } private: NON_COPYABLE(ProducerConsumerQueue); std::vector<T> buffer_; std::atomic<int> read_ {0}; std::atomic<int> write_ {0}; }; struct sample_buf { uint8_t* buf_ {nullptr}; // audio sample container size_t cap_ {0}; // buffer capacity in byte size_t size_ {0}; // audio sample size (n buf) in byte sample_buf() {} sample_buf(size_t alloc, size_t size) : buf_(new uint8_t[alloc]) , cap_(size) {} sample_buf(size_t alloc) : buf_(new uint8_t[alloc]) , cap_(alloc) {} sample_buf(sample_buf&& o) : buf_(o.buf_) , cap_(o.cap_) , size_(o.size_) { o.buf_ = nullptr; o.cap_ = 0; o.size_ = 0; } sample_buf& operator=(sample_buf&& o) { buf_ = o.buf_; cap_ = o.cap_; size_ = o.size_; o.buf_ = nullptr; o.cap_ = 0; o.size_ = 0; return *this; } ~sample_buf() { if (buf_) delete[] buf_; } NON_COPYABLE(sample_buf); }; using AudioQueue = ProducerConsumerQueue<sample_buf*>;
5,715
C++
.h
183
24.393443
83
0.584741
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,985
audio_common.h
savoirfairelinux_jami-daemon/src/media/audio/opensl/audio_common.h
/* * 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. */ #pragma once #include "../audio_format.h" #include "buf_manager.h" #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> namespace jami { namespace opensl { /* * Sample Buffer Controls... */ #define RECORD_DEVICE_KICKSTART_BUF_COUNT 4 #define PLAY_KICKSTART_BUFFER_COUNT 8 #define DEVICE_SHADOW_BUFFER_QUEUE_LEN 4 #define BUF_COUNT 16 inline SLAndroidDataFormat_PCM_EX convertToSLSampleFormat(const jami::AudioFormat& infos) { if (infos.sampleFormat == AV_SAMPLE_FMT_S16) return SLAndroidDataFormat_PCM_EX { .formatType = SL_DATAFORMAT_PCM, .numChannels = infos.nb_channels <= 1 ? 1u : 2u, .sampleRate = infos.sample_rate * 1000, .bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16, .containerSize = SL_PCMSAMPLEFORMAT_FIXED_16, .channelMask = infos.nb_channels <= 1 ? SL_SPEAKER_FRONT_CENTER : SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, .endianness = SL_BYTEORDER_LITTLEENDIAN, .representation = SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT, }; else if (infos.sampleFormat == AV_SAMPLE_FMT_FLT) return SLAndroidDataFormat_PCM_EX { .formatType = SL_ANDROID_DATAFORMAT_PCM_EX, .numChannels = infos.nb_channels <= 1 ? 1u : 2u, .sampleRate = infos.sample_rate * 1000, .bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_32, .containerSize = SL_PCMSAMPLEFORMAT_FIXED_32, .channelMask = infos.nb_channels <= 1 ? SL_SPEAKER_FRONT_CENTER : SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, .endianness = SL_BYTEORDER_LITTLEENDIAN, .representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT, }; else throw std::runtime_error("Unsupported sample format"); } #define SLASSERT(x) \ { \ if (SL_RESULT_SUCCESS != (x)) \ throw std::runtime_error("OpenSLES error " + std::to_string(x)); \ } /* * Interface for player and recorder to communicate with engine */ #define ENGINE_SERVICE_MSG_KICKSTART_PLAYER 1 #define ENGINE_SERVICE_MSG_RETRIEVE_DUMP_BUFS 2 using EngineCallback = std::function<void()>; } // namespace opensl } // namespace jami
2,991
C++
.h
73
34.547945
97
0.663114
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,986
audio_player.h
savoirfairelinux_jami-daemon/src/media/audio/opensl/audio_player.h
/* * 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. */ #pragma once #include "audio_common.h" #include "buf_manager.h" #include "noncopyable.h" #include <sys/types.h> #include <SLES/OpenSLES_Android.h> #include <mutex> namespace jami { namespace opensl { class AudioPlayer { // buffer queue player interfaces SLObjectItf outputMixObjectItf_; SLObjectItf playerObjectItf_; SLPlayItf playItf_; SLAndroidSimpleBufferQueueItf playBufferQueueItf_; jami::AudioFormat sampleInfo_; AudioQueue* freeQueue_ {nullptr}; // user AudioQueue* playQueue_ {nullptr}; // user AudioQueue devShadowQueue_ {DEVICE_SHADOW_BUFFER_QUEUE_LEN}; // owner sample_buf silentBuf_; EngineCallback callback_ {}; public: explicit AudioPlayer(jami::AudioFormat sampleFormat, size_t bufSize, SLEngineItf engine, SLint32 streamType); ~AudioPlayer(); NON_COPYABLE(AudioPlayer); bool start(); void stop(); bool started() const; void setBufQueue(AudioQueue* playQ, AudioQueue* freeQ); void processSLCallback(SLAndroidSimpleBufferQueueItf bq); void playAudioBuffers(unsigned count); void registerCallback(EngineCallback cb) { callback_ = cb; } size_t dbgGetDevBufCount(); std::mutex m_; }; } // namespace opensl } // namespace jami
2,034
C++
.h
57
31.263158
75
0.703157
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,987
opensllayer.h
savoirfairelinux_jami-daemon/src/media/audio/opensl/opensllayer.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 <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include <vector> #include <thread> #include "audio/audiolayer.h" #include "audio_player.h" #include "audio_recorder.h" class AudioPreference; #include "noncopyable.h" #include <memory> namespace jami { class RingBuffer; #define ANDROID_BUFFER_QUEUE_LENGTH 2U #define BUFFER_SIZE 512U #define MAX_NUMBER_INTERFACES 5 #define MAX_NUMBER_INPUT_DEVICES 3 /** * @file OpenSLLayer.h * @brief Main sound class for android. Manages the data transfers between the application and the * hardware. */ class OpenSLLayer : public AudioLayer { public: /** * Constructor */ OpenSLLayer(const AudioPreference& pref); /** * Destructor */ ~OpenSLLayer(); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold */ void startStream(AudioDeviceType stream = AudioDeviceType::ALL) override; /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state */ void stopStream(AudioDeviceType stream = AudioDeviceType::ALL) override; /** * Scan the sound card available for capture on the system * @return std::vector<std::string> The vector containing the string description of the card */ std::vector<std::string> getCaptureDeviceList() const override; /** * Scan the sound card available for capture on the system * @return std::vector<std::string> The vector containing the string description of the card */ std::vector<std::string> getPlaybackDeviceList() const override; void init(); void initAudioEngine(); void shutdownAudioEngine(); void startAudioCapture(); void stopAudioCapture(); virtual int getAudioDeviceIndex(const std::string&, AudioDeviceType) const override { return 0; } virtual std::string getAudioDeviceName(int, AudioDeviceType) const override { return ""; } void engineServicePlay(); void engineServiceRing(); void engineServiceRec(); private: /** * Get the index of the audio card for capture * @return int The index of the card used for capture * 0 for the first available card on the system, 1 ... */ virtual int getIndexCapture() const override { return 0; } /** * Get the index of the audio card for playback * @return int The index of the card used for playback * 0 for the first available card on the system, 1 ... */ virtual int getIndexPlayback() const override { return 0; } /** * Get the index of the audio card for ringtone (could be differnet from playback) * @return int The index of the card used for ringtone * 0 for the first available card on the system, 1 ... */ virtual int getIndexRingtone() const override { return 0; } uint32_t dbgEngineGetBufCount(); void dumpAvailableEngineInterfaces(); NON_COPYABLE(OpenSLLayer); virtual void updatePreference(AudioPreference& pref, int index, AudioDeviceType type) override; std::mutex recMtx {}; std::condition_variable recCv {}; /** * OpenSL standard object interface */ SLObjectItf engineObject_ {nullptr}; /** * OpenSL sound engine interface */ SLEngineItf engineInterface_ {nullptr}; AudioFormat hardwareFormat_ {AudioFormat::MONO()}; size_t hardwareBuffSize_ {BUFFER_SIZE}; std::vector<sample_buf> bufs_ {}; AudioQueue freePlayBufQueue_ {BUF_COUNT}; AudioQueue playBufQueue_ {BUF_COUNT}; AudioQueue freeRingBufQueue_ {BUF_COUNT}; AudioQueue ringBufQueue_ {BUF_COUNT}; AudioQueue freeRecBufQueue_ {BUF_COUNT}; // Owner of the queue AudioQueue recBufQueue_ {BUF_COUNT}; // Owner of the queue std::unique_ptr<opensl::AudioPlayer> player_ {}; std::unique_ptr<opensl::AudioPlayer> ringtone_ {}; std::unique_ptr<opensl::AudioRecorder> recorder_ {}; std::thread recThread {}; }; } // namespace jami
4,866
C++
.h
127
33.984252
101
0.703767
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,988
audio_recorder.h
savoirfairelinux_jami-daemon/src/media/audio/opensl/audio_recorder.h
/* * 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. */ #pragma once #include <sys/types.h> #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include "audio_common.h" #include "buf_manager.h" #include "noncopyable.h" namespace jami { namespace opensl { class AudioRecorder { SLObjectItf recObjectItf_; SLRecordItf recItf_; SLAndroidSimpleBufferQueueItf recBufQueueItf_; jami::AudioFormat sampleInfo_; AudioQueue* freeQueue_ {nullptr}; // user AudioQueue* recQueue_ {nullptr}; // user AudioQueue devShadowQueue_ {DEVICE_SHADOW_BUFFER_QUEUE_LEN}; // owner uint32_t audioBufCount; sample_buf silentBuf_; EngineCallback callback_ {}; bool hasNativeAEC_ {false}; bool hasNativeNS_ {false}; public: explicit AudioRecorder(jami::AudioFormat, size_t bufSize, SLEngineItf engineEngine); ~AudioRecorder(); NON_COPYABLE(AudioRecorder); bool start(); bool stop(); void setBufQueues(AudioQueue* freeQ, AudioQueue* recQ); void processSLCallback(SLAndroidSimpleBufferQueueItf bq); void registerCallback(EngineCallback cb) { callback_ = cb; } size_t dbgGetDevBufCount(); bool hasNativeAEC() const { return hasNativeAEC_; } bool hasNativeNS() const { return hasNativeNS_; } }; } // namespace opensl } // namespace jami
1,980
C++
.h
54
33.481481
88
0.725849
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,989
audiostream.h
savoirfairelinux_jami-daemon/src/media/audio/pulseaudio/audiostream.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 "noncopyable.h" #include "pulselayer.h" #include <pulse/pulseaudio.h> #include <string> namespace jami { inline AVSampleFormat sampleFormatFromPulse(pa_sample_format_t format) { switch (format) { case PA_SAMPLE_S16LE: case PA_SAMPLE_S16BE: return AV_SAMPLE_FMT_S16; case PA_SAMPLE_FLOAT32LE: case PA_SAMPLE_FLOAT32BE: return AV_SAMPLE_FMT_FLT; case PA_SAMPLE_S32LE: case PA_SAMPLE_S32BE: return AV_SAMPLE_FMT_S32; default: return AV_SAMPLE_FMT_S16; } } inline pa_sample_format_t pulseSampleFormatFromAv(AVSampleFormat format) { switch (format) { case AV_SAMPLE_FMT_S16: return PA_SAMPLE_S16LE; case AV_SAMPLE_FMT_FLT: return PA_SAMPLE_FLOAT32LE; case AV_SAMPLE_FMT_S32: return PA_SAMPLE_S32LE; default: return PA_SAMPLE_S16LE; } } class AudioStream { public: using OnReady = std::function<void()>; using OnData = std::function<void(size_t)>; /** * Constructor * * @param context pulseaudio's application context. * @param mainloop pulseaudio's main loop * @param description * @param types * @param audio sampling rate * @param pointer to pa_source_info or pa_sink_info (depending on type). * @param true if echo cancelling should be used with this stream */ AudioStream(pa_context*, pa_threaded_mainloop*, const char*, AudioDeviceType, unsigned, pa_sample_format_t, const PaDeviceInfos&, bool, OnReady onReady, OnData onData); ~AudioStream(); void start(); void stop(); /** * Accessor: Get the pulseaudio stream object * @return pa_stream* The stream */ pa_stream* stream() { return audiostream_; } const pa_sample_spec* sampleSpec() const { return pa_stream_get_sample_spec(audiostream_); } inline size_t sampleSize() const { return pa_sample_size(sampleSpec()); } inline size_t frameSize() const { return pa_frame_size(sampleSpec()); } inline uint8_t channels() const { return sampleSpec()->channels; } inline AudioFormat format() const { auto s = sampleSpec(); return AudioFormat(s->rate, s->channels, sampleFormatFromPulse(s->format)); } inline std::string getDeviceName() const { auto res = pa_stream_get_device_name(audiostream_); if (res == reinterpret_cast<decltype(res)>(-PA_ERR_NOTSUPPORTED) or !res) return {}; return res; } bool isReady(); void setEchoCancelCb(std::function<void(bool)>&& cb) { echoCancelCb = cb; } private: NON_COPYABLE(AudioStream); OnReady onReady_; OnData onData_; /** * Mandatory asynchronous callback on the audio stream state */ void stateChanged(pa_stream* s); void moved(pa_stream* s); void opEnded(pa_operation* s); /** * The pulse audio object */ pa_stream* audiostream_; /** * A pointer to the opaque threaded main loop object */ pa_threaded_mainloop* mainloop_; /** * The type of this audio stream */ AudioDeviceType audioType_; /** * Function called whenever the stream is moved and we check for an echo canceller */ std::function<void(bool)> echoCancelCb; std::mutex mutex_; std::condition_variable cond_; std::set<pa_operation*> ongoing_ops; }; } // namespace jami
4,175
C++
.h
136
25.727941
96
0.674059
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,990
pulselayer.h
savoirfairelinux_jami-daemon/src/media/audio/pulseaudio/pulselayer.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 "noncopyable.h" #include "logger.h" #include "audio/audiolayer.h" #include <pulse/pulseaudio.h> #include <pulse/stream.h> #include <list> #include <string> #include <memory> #include <thread> namespace jami { class AudioPreference; class AudioStream; class RingBuffer; /** * Convenience structure to hold PulseAudio device propreties such as supported channel number etc. */ struct PaDeviceInfos { uint32_t index {0}; std::string name {}; std::string description {"default"}; pa_sample_spec sample_spec {}; pa_channel_map channel_map {}; uint32_t monitor_of {PA_INVALID_INDEX}; PaDeviceInfos() {} PaDeviceInfos(const pa_source_info& source) : index(source.index) , name(source.name) , description(source.description) , sample_spec(source.sample_spec) , channel_map(source.channel_map) , monitor_of(source.monitor_of_sink) {} PaDeviceInfos(const pa_sink_info& source) : index(source.index) , name(source.name) , description(source.description) , sample_spec(source.sample_spec) , channel_map(source.channel_map) {} /** * Unary function to search for a device by name in a list using std functions. */ class NameComparator { public: explicit NameComparator(const std::string& ref) : baseline(ref) {} bool operator()(const PaDeviceInfos& arg) { return arg.name == baseline; } private: const std::string& baseline; }; class DescriptionComparator { public: explicit DescriptionComparator(const std::string& ref) : baseline(ref) {} bool operator()(const PaDeviceInfos& arg) { return arg.description == baseline; } private: const std::string& baseline; }; }; class PulseMainLoopLock { public: explicit PulseMainLoopLock(pa_threaded_mainloop* loop); ~PulseMainLoopLock(); private: NON_COPYABLE(PulseMainLoopLock); pa_threaded_mainloop* loop_; }; class PulseLayer : public AudioLayer { public: PulseLayer(AudioPreference& pref); ~PulseLayer(); /** * Write data from the ring buffer to the hardware and read data * from the hardware. */ void readFromMic(); void writeToSpeaker(); void ringtoneToSpeaker(); void updateSinkList(); void updateSourceList(); void updateServerInfo(); bool inSinkList(const std::string& deviceName); bool inSourceList(const std::string& deviceName); virtual std::vector<std::string> getCaptureDeviceList() const; virtual std::vector<std::string> getPlaybackDeviceList() const; int getAudioDeviceIndex(const std::string& descr, AudioDeviceType type) const; int getAudioDeviceIndexByName(const std::string& name, AudioDeviceType type) const; std::string getAudioDeviceName(int index, AudioDeviceType type) const; virtual void startStream(AudioDeviceType stream = AudioDeviceType::ALL); virtual void stopStream(AudioDeviceType stream = AudioDeviceType::ALL); private: static void context_state_callback(pa_context* c, void* user_data); static void context_changed_callback(pa_context* c, pa_subscription_event_type_t t, uint32_t idx, void* userdata); void contextStateChanged(pa_context* c); void contextChanged(pa_context*, pa_subscription_event_type_t, uint32_t idx); static void source_input_info_callback(pa_context* c, const pa_source_info* i, int eol, void* userdata); static void sink_input_info_callback(pa_context* c, const pa_sink_info* i, int eol, void* userdata); static void server_info_callback(pa_context*, const pa_server_info* i, void* userdata); virtual void updatePreference(AudioPreference& pref, int index, AudioDeviceType type); virtual int getIndexCapture() const; virtual int getIndexPlayback() const; virtual int getIndexRingtone() const; void waitForDevices(); void waitForDeviceList(); std::string getPreferredPlaybackDevice() const; std::string getPreferredRingtoneDevice() const; std::string getPreferredCaptureDevice() const; NON_COPYABLE(PulseLayer); /** * Create the audio stream */ void createStream(std::unique_ptr<AudioStream>& stream, AudioDeviceType type, const PaDeviceInfos& dev_infos, bool ec, std::function<void(size_t)>&& onData); std::unique_ptr<AudioStream>& getStream(AudioDeviceType type) { if (type == AudioDeviceType::PLAYBACK) return playback_; else if (type == AudioDeviceType::RINGTONE) return ringtone_; else if (type == AudioDeviceType::CAPTURE) return record_; else return playback_; } /** * Close the connection with the local pulseaudio server */ void disconnectAudioStream(); void onStreamReady(); /** * Returns a pointer to the PaEndpointInfos with the given name in sourceList_, or nullptr if * not found. */ const PaDeviceInfos* getDeviceInfos(const std::vector<PaDeviceInfos>&, const std::string& name) const; std::atomic_uint pendingStreams {0}; /** * A stream object to handle the pulseaudio playback stream */ std::unique_ptr<AudioStream> playback_; /** * A stream object to handle the pulseaudio capture stream */ std::unique_ptr<AudioStream> record_; /** * A special stream object to handle specific playback stream for ringtone */ std::unique_ptr<AudioStream> ringtone_; /** * Contains the list of playback devices */ std::vector<PaDeviceInfos> sinkList_ {}; /** * Contains the list of capture devices */ std::vector<PaDeviceInfos> sourceList_ {}; /** PulseAudio server defaults */ AudioFormat defaultAudioFormat_ {AudioFormat::MONO()}; std::string defaultSink_ {}; std::string defaultSource_ {}; /** PulseAudio context and asynchronous loop */ pa_context* context_ {nullptr}; std::unique_ptr<pa_threaded_mainloop, decltype(pa_threaded_mainloop_free)&> mainloop_; bool enumeratingSinks_ {false}; bool enumeratingSources_ {false}; bool gettingServerInfo_ {false}; std::atomic_bool waitingDeviceList_ {false}; std::mutex readyMtx_ {}; std::condition_variable readyCv_ {}; std::thread streamStarter_ {}; AudioPreference& preference_; pa_operation* subscribeOp_ {nullptr}; friend class AudioLayerTest; }; } // namespace jami
7,664
C++
.h
207
30.043478
161
0.662485
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,991
alsalayer.h
savoirfairelinux_jami-daemon/src/media/audio/alsa/alsalayer.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 "audio/audiolayer.h" #include "noncopyable.h" #include <alsa/asoundlib.h> #include <memory> #include <thread> #define PCM_DMIX "plug:dmix" /** Alsa plugin for software mixing */ // Error codes for error handling #define ALSA_CAPTURE_DEVICE 0x0001 /** Error while opening capture device */ #define ALSA_PLAYBACK_DEVICE 0x0010 /** Error while opening playback device */ /** * @file AlsaLayer.h * @brief Main sound class. Manages the data transfers between the application and the hardware. */ namespace jami { class AlsaThread; class RingBuffer; class AudioPreference; /** Associate a sound card index to its string description */ typedef std::pair<int, std::string> HwIDPair; class AlsaLayer : public AudioLayer { public: /** * Constructor */ AlsaLayer(const AudioPreference& pref); /** * Destructor */ ~AlsaLayer(); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold * ALSA Library API */ virtual void startStream(AudioDeviceType stream = AudioDeviceType::ALL); /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state * ALSA Library API */ virtual void stopStream(AudioDeviceType stream = AudioDeviceType::ALL); /** * Concatenate two strings. Used to build a valid pcm device name. * @param plugin the alsa PCM name * @param card the sound card number * @return std::string the concatenated string */ std::string buildDeviceTopo(const std::string& plugin, int card); /** * Scan the sound card available on the system * @return std::vector<std::string> The vector containing the string description of the card */ virtual std::vector<std::string> getCaptureDeviceList() const; virtual std::vector<std::string> getPlaybackDeviceList() const; /** * Check if the given index corresponds to an existing sound card and supports the specified *streaming mode * @param card An index * @param stream The stream mode * AudioDeviceType::CAPTURE * AudioDeviceType::PLAYBACK * AudioDeviceType::RINGTONE * @return bool True if it exists and supports the mode * false otherwise */ static bool soundCardIndexExists(int card, AudioDeviceType stream); /** * An index is associated with its string description * @param description The string description * @return int Its index */ int getAudioDeviceIndex(const std::string& description, AudioDeviceType type) const; std::string getAudioDeviceName(int index, AudioDeviceType type) const; void playback(); void ringtone(); void capture(); /** * Get the index of the audio card for capture * @return int The index of the card used for capture * 0 for the first available card on the system, 1 ... */ virtual int getIndexCapture() const { return indexIn_; } /** * Get the index of the audio card for playback * @return int The index of the card used for playback * 0 for the first available card on the system, 1 ... */ virtual int getIndexPlayback() const { return indexOut_; } /** * Get the index of the audio card for ringtone (could be differnet from playback) * @return int The index of the card used for ringtone * 0 for the first available card on the system, 1 ... */ virtual int getIndexRingtone() const { return indexRing_; } void run(); private: /** * Returns a map of audio device hardware description and index */ std::vector<HwIDPair> getAudioDeviceIndexMap(bool getCapture) const; /** * Calls snd_pcm_open and retries if device is busy, since dmix plugin * will often hold on to a device temporarily after it has been opened * and closed. */ bool openDevice(snd_pcm_t** pcm, const std::string& dev, snd_pcm_stream_t stream, AudioFormat& format); /** * Number of audio cards on which capture stream has been opened */ int indexIn_; /** * Number of audio cards on which playback stream has been opened */ int indexOut_; /** * Number of audio cards on which ringtone stream has been opened */ int indexRing_; NON_COPYABLE(AlsaLayer); /** * Drop the pending frames and close the capture device * ALSA Library API */ void closeCaptureStream(); void stopCaptureStream(); void startCaptureStream(); void prepareCaptureStream(); void closePlaybackStream(); void stopPlaybackStream(); void startPlaybackStream(); void closeRingtoneStream(); bool alsa_set_params(snd_pcm_t* pcm_handle, AudioFormat& format); void startThread(); void stopThread(); /** * Copy a data buffer in the internal ring buffer * ALSA Library API * @param buffer The non-interleaved data to be copied * @param frames Frames in the buffer */ void write(const AudioFrame& buffer, snd_pcm_t* handle); /** * Read data from the internal ring buffer * ALSA Library API * @param buffer The buffer to stock the read data * @param frames The number of frames to get * @return int The number of frames actually read */ std::unique_ptr<AudioFrame> read(unsigned frames); virtual void updatePreference(AudioPreference& pref, int index, AudioDeviceType type); /** * Handles to manipulate playback stream * ALSA Library API */ snd_pcm_t* playbackHandle_ {nullptr}; /** * Handles to manipulate ringtone stream * */ snd_pcm_t* ringtoneHandle_ {nullptr}; /** * Handles to manipulate capture stream * ALSA Library API */ snd_pcm_t* captureHandle_ {nullptr}; /** * name of the alsa audio plugin used */ std::string audioPlugin_; bool is_capture_prepared_ {false}; bool is_playback_running_ {false}; bool is_capture_running_ {false}; bool is_playback_open_ {false}; bool is_capture_open_ {false}; std::atomic_bool running_ {false}; std::thread audioThread_; }; } // namespace jami
7,125
C++
.h
199
30.688442
96
0.679402
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,992
tone.h
savoirfairelinux_jami-daemon/src/media/audio/sound/tone.h
/* * 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/>. */ #pragma once #include <string> #include "audio/audioloop.h" /** * @file tone.h * @brief Tone sample (dial, busy, ring, congestion) */ namespace jami { class Tone : public AudioLoop { public: /** * Constructor * @param definition String that contain frequency/time of the tone * @param sampleRate SampleRating of audio tone */ Tone(std::string_view definition, unsigned int sampleRate, AVSampleFormat sampleFormat); /** The different kind of tones */ enum class ToneId { DIALTONE = 0, BUSY, RINGTONE, CONGESTION, TONE_NULL }; /** * Add a simple or double sin to the buffer, it double the sin in stereo * @param buffer The data * @param frequency1 The first frequency * @param frequency2 The second frequency * @param nb the number of samples to generate */ static void genSin(AVFrame* buffer, size_t outPos, unsigned nb_samples, unsigned frequency1, unsigned frequency2); private: /** * allocate the memory with the definition * @param definition String that contain frequency/time of the tone. */ void genBuffer(std::string_view definition); }; } // namespace jami
1,990
C++
.h
54
33.518519
118
0.72251
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,993
dtmfgenerator.h
savoirfairelinux_jami-daemon/src/media/audio/sound/dtmfgenerator.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 <stdexcept> #include <string> #include <vector> #include "noncopyable.h" #include "tone.h" #define NUM_TONES 16 /* * @file dtmfgenerator.h * @brief DMTF Generator Exception */ namespace jami { class DTMFException : public std::runtime_error { public: DTMFException(const std::string& str) : std::runtime_error(str) {}; }; /* * @file dtmfgenerator.h * @brief DTMF Tone Generator */ class DTMFGenerator { private: /** Struct to handle a DTMF */ struct DTMFTone { unsigned char code; /** Code of the tone */ unsigned lower; /** Lower frequency */ unsigned higher; /** Higher frequency */ }; /** State of the DTMF generator */ struct DTMFState { unsigned int offset; /** Offset in the sample currently being played */ AVFrame* sample; /** Currently generated code */ }; /** State of the DTMF generator */ DTMFState state; /** The different kind of tones */ static const DTMFTone tones_[NUM_TONES]; /** Generated samples for each tone */ std::array<libjami::FrameBuffer, NUM_TONES> toneBuffers_; /** Sampling rate of generated dtmf */ unsigned sampleRate_; /** A tone object */ Tone tone_; public: /** * DTMF Generator contains frequency of each keys * and can build one DTMF. * @param sampleRate frequency of the sample (ex: 8000 hz) */ DTMFGenerator(unsigned int sampleRate, AVSampleFormat sampleFormat); ~DTMFGenerator(); NON_COPYABLE(DTMFGenerator); /* * Get n samples of the signal of code code * @param frame the output AVFrame to fill * @param code dtmf code to get sound */ void getSamples(AVFrame* frame, unsigned char code); /* * Get next n samples (continues where previous call to * genSample or genNextSamples stopped * @param buffer a AudioSample vector */ void getNextSamples(AVFrame* frame); private: /** * Fill tone buffer for a given index of the array of tones. * @param index of the tone in the array tones_ * @return AudioSample* The generated data */ libjami::FrameBuffer fillToneBuffer(int index); }; } // namespace jami
2,967
C++
.h
94
27.542553
79
0.685004
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,994
dtmf.h
savoirfairelinux_jami-daemon/src/media/audio/sound/dtmf.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 "dtmfgenerator.h" /** * @file dtmf.h * @brief DMTF library to generate a dtmf sample */ namespace jami { class DTMF { public: /** * Create a new DTMF. * @param sampleRate frequency of the sample (ex: 8000 hz) */ DTMF(unsigned int sampleRate, AVSampleFormat sampleFormat); /** * Start the done for th given dtmf * @param code The DTMF code */ void startTone(char code); /** * Copy the sound inside the sampling* buffer */ bool generateDTMF(AVFrame* frame); private: char currentTone_; char newTone_; DTMFGenerator dtmfgenerator_; }; } // namespace jami
1,379
C++
.h
46
26.76087
73
0.708679
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,995
audiofile.h
savoirfairelinux_jami-daemon/src/media/audio/sound/audiofile.h
/* * 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/>. */ #pragma once #include <stdexcept> #include "audio/audioloop.h" namespace jami { class AudioFileException : public std::runtime_error { public: AudioFileException(const std::string& str) : std::runtime_error("AudioFile: AudioFileException occurred: " + str) {} }; /** * @brief Abstract interface for file readers */ class AudioFile : public AudioLoop { public: AudioFile(const std::string& filepath, unsigned int sampleRate, AVSampleFormat sampleFormat); std::string getFilePath() const { return filepath_; } protected: /** The absolute path to the sound file */ std::string filepath_; private: // override void onBufferFinish(); unsigned updatePlaybackScale_; }; } // namespace jami
1,600
C++
.h
48
30.8125
97
0.743523
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,996
tonelist.h
savoirfairelinux_jami-daemon/src/media/audio/sound/tonelist.h
/* * 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/>. */ #pragma once #include "tone.h" #include <string> #include <array> #include <memory> namespace jami { class TelephoneTone { public: /** Countries */ enum class CountryId { ZID_NORTH_AMERICA = 0, ZID_FRANCE, ZID_AUSTRALIA, ZID_UNITED_KINGDOM, ZID_SPAIN, ZID_ITALY, ZID_JAPAN, ZID_COUNTRIES, }; TelephoneTone(const std::string& countryName, unsigned int sampleRate, AVSampleFormat sampleFormat); void setCurrentTone(Tone::ToneId toneId); void setSampleRate(unsigned int sampleRate, AVSampleFormat sampleFormat); std::shared_ptr<Tone> getCurrentTone(); private: NON_COPYABLE(TelephoneTone); static CountryId getCountryId(const std::string& countryName); void buildTones(unsigned int sampleRate, AVSampleFormat sampleFormat); CountryId countryId_; std::array<std::shared_ptr<Tone>, (size_t) Tone::ToneId::TONE_NULL> tones_ {}; Tone::ToneId currentTone_; }; } // namespace jami
1,815
C++
.h
52
31.115385
104
0.724886
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,997
corelayer.h
savoirfairelinux_jami-daemon/src/media/audio/coreaudio/osx/corelayer.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/>. */ #ifndef CORE_LAYER_H_ #define CORE_LAYER_H_ #include "audio/audiolayer.h" #include <AudioToolbox/AudioToolbox.h> #define checkErr(err) \ if (err) { \ OSStatus error = static_cast<OSStatus>(err); \ fprintf(stdout, "CoreAudio Error: %ld -> %s: %d\n", (long) error, __FILE__, __LINE__); \ fflush(stdout); \ } /** * @file CoreLayer.h * @brief Main OSX sound class. Manages the data transfers between the application and the hardware. */ namespace jami { class RingBuffer; class AudioDevice; class CoreLayer : public AudioLayer { public: CoreLayer(const AudioPreference& pref); ~CoreLayer(); /** * Scan the sound card available on the system * @return std::vector<std::string> The vector containing the string description of the card */ virtual std::vector<std::string> getCaptureDeviceList() const; virtual std::vector<std::string> getPlaybackDeviceList() const; virtual int getAudioDeviceIndex(const std::string& name, AudioDeviceType type) const; virtual std::string getAudioDeviceName(int index, AudioDeviceType type) const; /** * Get the index of the audio card for capture * @return int The index of the card used for capture */ virtual int getIndexCapture() const { return indexIn_; } /** * Get the index of the audio card for playback * @return int The index of the card used for playback */ virtual int getIndexPlayback() const { return indexOut_; } /** * Get the index of the audio card for ringtone (could be differnet from playback) * @return int The index of the card used for ringtone */ virtual int getIndexRingtone() const { return indexRing_; } /** * Configure the AudioUnit */ void initAudioLayerIO(AudioDeviceType stream); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold * CoreAudio Library API */ virtual void startStream(AudioDeviceType stream = AudioDeviceType::ALL); void destroyAudioLayer(); /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state * CoreAudio Library API */ virtual void stopStream(AudioDeviceType stream = AudioDeviceType::ALL); private: NON_COPYABLE(CoreLayer); void initAudioFormat(); static OSStatus outputCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); void write(AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); static OSStatus inputCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); static OSStatus deviceIsAliveCallback(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void* inRefCon); static OSStatus devicesChangedCallback(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress inAddresses[], void* inRefCon); void read(AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); virtual void updatePreference(AudioPreference& pref, int index, AudioDeviceType type); /** * Number of audio cards on which capture stream has been opened */ int indexIn_; /** * Number of audio cards on which playback stream has been opened */ int indexOut_; /** * Number of audio cards on which ringtone stream has been opened */ int indexRing_; AudioUnit ioUnit_; Float64 inSampleRate_; UInt32 inChannelsPerFrame_; Float64 outSampleRate_; UInt32 outChannelsPerFrame_; std::vector<AudioDevice> getDeviceList(bool getCapture) const; }; } // namespace jami #endif // CORE_LAYER_H_
5,566
C++
.h
133
32.56391
100
0.644325
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,998
audiodevice.h
savoirfairelinux_jami-daemon/src/media/audio/coreaudio/osx/audiodevice.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/>. */ #ifndef AUDIO_DEVICE_H #define AUDIO_DEVICE_H #import <TargetConditionals.h> #if !TARGET_OS_IPHONE #include <CoreServices/CoreServices.h> #include <CoreAudio/CoreAudio.h> #endif #include <string> namespace jami { class AudioDevice { #if !TARGET_OS_IPHONE public: AudioDevice() : id_(kAudioDeviceUnknown) {} AudioDevice(AudioDeviceID devid, bool isInput); void init(AudioDeviceID devid, bool isInput); bool valid() const; void setBufferSize(UInt32 size); public: AudioDeviceID id_; std::string name_; bool isInput_; int channels_; UInt32 safetyOffset_; UInt32 bufferSizeFrames_; AudioStreamBasicDescription format_; private: int countChannels() const; std::string getName() const; #endif }; } // namespace jami #endif /* defined(AUDIO_DEVICE_H) */
1,542
C++
.h
51
27.411765
73
0.741391
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,999
corelayer.h
savoirfairelinux_jami-daemon/src/media/audio/coreaudio/ios/corelayer.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/>. */ #ifndef CORE_LAYER_H_ #define CORE_LAYER_H_ #include "audio/audiolayer.h" #include <AudioToolbox/AudioToolbox.h> #define checkErr(err) \ if (err) { \ JAMI_ERR("CoreAudio Error: %ld", static_cast<long>(err)); \ } /** * @file CoreLayer.h * @brief Main iOS sound class. Manages the data transfers between the application and the hardware. */ namespace jami { class RingBuffer; class CoreLayer : public AudioLayer { public: CoreLayer(const AudioPreference& pref); ~CoreLayer(); /** * Scan the sound card available on the system * @return std::vector<std::string> The vector containing the string description of the card */ virtual std::vector<std::string> getCaptureDeviceList() const; virtual std::vector<std::string> getPlaybackDeviceList() const; virtual int getAudioDeviceIndex(const std::string& name, AudioDeviceType type) const; virtual std::string getAudioDeviceName(int index, AudioDeviceType type) const; /** * Get the index of the audio card for capture * @return int The index of the card used for capture */ virtual int getIndexCapture() const { return indexIn_; } /** * Get the index of the audio card for playback * @return int The index of the card used for playback */ virtual int getIndexPlayback() const { return indexOut_; } /** * Get the index of the audio card for ringtone (could be differnet from playback) * @return int The index of the card used for ringtone */ virtual int getIndexRingtone() const { return indexRing_; } /** * Configure the AudioUnit */ bool initAudioLayerIO(AudioDeviceType stream); void setupOutputBus(); void setupInputBus(); void bindCallbacks(); int initAudioStreams(AudioUnit* audioUnit); /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold * CoreAudio Library API */ virtual void startStream(AudioDeviceType stream = AudioDeviceType::ALL); void destroyAudioLayer(); /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state * CoreAudio Library API */ virtual void stopStream(AudioDeviceType stream = AudioDeviceType::ALL); private: NON_COPYABLE(CoreLayer); void initAudioFormat(); static OSStatus outputCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); void write(AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); static OSStatus inputCallback(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); void read(AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); virtual void updatePreference(AudioPreference& pref, int index, AudioDeviceType type); /** * Number of audio cards on which capture stream has been opened */ int indexIn_; /** * Number of audio cards on which playback stream has been opened */ int indexOut_; /** * Number of audio cards on which ringtone stream has been opened */ int indexRing_; AudioUnit ioUnit_; Float64 inSampleRate_; UInt32 inChannelsPerFrame_; Float64 outSampleRate_; UInt32 outChannelsPerFrame_; std::condition_variable readyCv_ {}; dispatch_queue_t audioConfigurationQueue; }; } // namespace jami #endif // CORE_LAYER_H_
5,009
C++
.h
127
31.795276
100
0.667973
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
752,000
portaudiolayer.h
savoirfairelinux_jami-daemon/src/media/audio/portaudio/portaudiolayer.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 "audio/audiolayer.h" #include "noncopyable.h" #include <memory> #include <array> namespace jami { class PortAudioLayer final : public AudioLayer { public: PortAudioLayer(const AudioPreference& pref); ~PortAudioLayer(); std::vector<std::string> getCaptureDeviceList() const override; std::vector<std::string> getPlaybackDeviceList() const override; int getAudioDeviceIndex(const std::string& name, AudioDeviceType type) const override; std::string getAudioDeviceName(int index, AudioDeviceType type) const override; int getIndexCapture() const override; int getIndexPlayback() const override; int getIndexRingtone() const override; /** * Start the capture stream and prepare the playback stream. * The playback starts accordingly to its threshold */ void startStream(AudioDeviceType stream = AudioDeviceType::ALL) override; /** * Stop the playback and capture streams. * Drops the pending frames and put the capture and playback handles to PREPARED state */ void stopStream(AudioDeviceType stream = AudioDeviceType::ALL) override; void updatePreference(AudioPreference& pref, int index, AudioDeviceType type) override; private: NON_COPYABLE(PortAudioLayer); struct PortAudioLayerImpl; std::unique_ptr<PortAudioLayerImpl> pimpl_; }; } // namespace jami
2,099
C++
.h
51
37.72549
91
0.756996
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
752,001
speex.h
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/speex.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 "audio_processor.h" // typedef speex C structs extern "C" { struct SpeexEchoState_; typedef struct SpeexEchoState_ SpeexEchoState; struct SpeexPreprocessState_; typedef struct SpeexPreprocessState_ SpeexPreprocessState; } namespace jami { class SpeexAudioProcessor final : public AudioProcessor { public: SpeexAudioProcessor(AudioFormat format, unsigned frameSize); ~SpeexAudioProcessor() = default; std::shared_ptr<AudioFrame> getProcessed() override; void enableEchoCancel(bool enabled) override; void enableNoiseSuppression(bool enabled) override; void enableAutomaticGainControl(bool enabled) override; void enableVoiceActivityDetection(bool enabled) override; private: using SpeexEchoStatePtr = std::unique_ptr<SpeexEchoState, void (*)(SpeexEchoState*)>; using SpeexPreprocessStatePtr = std::unique_ptr<SpeexPreprocessState, void (*)(SpeexPreprocessState*)>; // multichannel, one for the entire audio processor SpeexEchoStatePtr echoState; // one for each channel std::vector<SpeexPreprocessStatePtr> preprocessorStates; std::unique_ptr<AudioFrame> procBuffer {}; Resampler deinterleaveResampler; Resampler interleaveResampler; // if we should do echo cancellation bool shouldAEC {false}; // if we should do voice activity detection // preprocess_run returns 1 if vad is disabled, so we have to know whether or not to ignore it bool shouldDetectVoice {false}; }; } // namespace jami
2,297
C++
.h
54
38.111111
99
0.75169
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
752,002
null_audio_processor.h
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/null_audio_processor.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 "audio_processor.h" namespace jami { class NullAudioProcessor final : public AudioProcessor { public: NullAudioProcessor(AudioFormat format, unsigned frameSize); ~NullAudioProcessor() = default; std::shared_ptr<AudioFrame> getProcessed() override; void enableEchoCancel(bool) override {}; void enableNoiseSuppression(bool) override {}; void enableAutomaticGainControl(bool) override {}; void enableVoiceActivityDetection(bool) override {}; }; } // namespace jami
1,279
C++
.h
31
37.290323
74
0.74065
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
752,003
webrtc.h
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/webrtc.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 "audio_processor.h" namespace webrtc { class AudioProcessing; } namespace jami { class WebRTCAudioProcessor final : public AudioProcessor { public: WebRTCAudioProcessor(AudioFormat format, unsigned frameSize); ~WebRTCAudioProcessor() = default; // Inherited via AudioProcessor std::shared_ptr<AudioFrame> getProcessed() override; void enableEchoCancel(bool enabled) override; void enableNoiseSuppression(bool enabled) override; void enableAutomaticGainControl(bool enabled) override; void enableVoiceActivityDetection(bool enabled) override; private: std::unique_ptr<webrtc::AudioProcessing> apm; int analogLevel_ {0}; }; } // namespace jami
1,473
C++
.h
38
34.947368
74
0.748768
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
752,004
audio_processor.h
savoirfairelinux_jami-daemon/src/media/audio/audio-processing/audio_processor.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 "noncopyable.h" #include "media/audio/audio_frame_resizer.h" #include "media/audio/resampler.h" #include "media/audio/audio_format.h" #include "media/libav_deps.h" #include "logger.h" #include <atomic> #include <memory> namespace jami { class AudioProcessor { private: NON_COPYABLE(AudioProcessor); public: AudioProcessor(AudioFormat format, unsigned frameSize) : playbackQueue_(format, (int) frameSize) , recordQueue_(format, (int) frameSize) , resampler_(new Resampler) , format_(format) , frameSize_(frameSize) , frameDurationMs_((unsigned int) (frameSize_ * (1.0 / format_.sample_rate) * 1000)) {} virtual ~AudioProcessor() = default; virtual void putRecorded(std::shared_ptr<AudioFrame>&& buf) { recordStarted_ = true; if (!playbackStarted_) return; enqueue(recordQueue_, std::move(buf)); }; virtual void putPlayback(const std::shared_ptr<AudioFrame>& buf) { playbackStarted_ = true; if (!recordStarted_) return; auto copy = buf; enqueue(playbackQueue_, std::move(copy)); }; /** * @brief Process and return a single AudioFrame */ virtual std::shared_ptr<AudioFrame> getProcessed() = 0; /** * @brief Set the status of echo cancellation */ virtual void enableEchoCancel(bool enabled) = 0; /** * @brief Set the status of noise suppression * includes de-reverb, de-noise, high pass filter, etc */ virtual void enableNoiseSuppression(bool enabled) = 0; /** * @brief Set the status of automatic gain control */ virtual void enableAutomaticGainControl(bool enabled) = 0; /** * @brief Set the status of voice activity detection */ virtual void enableVoiceActivityDetection(bool enabled) = 0; protected: AudioFrameResizer playbackQueue_; AudioFrameResizer recordQueue_; std::unique_ptr<Resampler> resampler_; std::atomic_bool playbackStarted_; std::atomic_bool recordStarted_; AudioFormat format_; unsigned int frameSize_; unsigned int frameDurationMs_; // artificially extend voice activity by this long unsigned int forceMinimumVoiceActivityMs {1000}; // current number of frames to force the voice activity to be true unsigned int forceVoiceActiveFramesLeft {0}; // voice activity must be active for this long _before_ it is considered legitimate unsigned int minimumConsequtiveDurationMs {200}; // current number of frames that the voice activity has been true unsigned int consecutiveActiveFrames {0}; /** * @brief Helper method for audio processors, should be called at start of getProcessed() * Pops frames from audio queues if there's overflow * @returns True if there is underflow, false otherwise. An AudioProcessor should * return a blank AudioFrame if there is underflow. */ bool tidyQueues() { auto recordFrameSize = recordQueue_.frameSize(); auto playbackFrameSize = playbackQueue_.frameSize(); while (recordQueue_.samples() > recordFrameSize * 10 && 2 * playbackQueue_.samples() * recordFrameSize < recordQueue_.samples() * playbackFrameSize) { JAMI_LOG("record overflow {:d} / {:d} - playback: {:d}", recordQueue_.samples(), frameSize_, playbackQueue_.samples()); recordQueue_.dequeue(); } while (playbackQueue_.samples() > playbackFrameSize * 10 && 2 * recordQueue_.samples() * playbackFrameSize < playbackQueue_.samples() * recordFrameSize) { JAMI_LOG("playback overflow {:d} / {:d} - record: {:d}", playbackQueue_.samples(), frameSize_, recordQueue_.samples()); playbackQueue_.dequeue(); } if (recordQueue_.samples() < recordFrameSize || playbackQueue_.samples() < playbackFrameSize) { // If there are not enough samples in either queue, we are unable to // process anything. return true; } return false; } /** * @brief Stablilizes voice activity * @param voiceStatus the voice status that was detected by the audio processor * for the current frame * @returns The voice activity status that should be set on the current frame */ bool getStabilizedVoiceActivity(bool voiceStatus) { bool newVoice = false; if (voiceStatus) { // we detected activity consecutiveActiveFrames += 1; // make sure that we have been active for necessary time if (consecutiveActiveFrames > minimumConsequtiveDurationMs / frameDurationMs_) { newVoice = true; // set number of frames that will be forced positive forceVoiceActiveFramesLeft = (int) forceMinimumVoiceActivityMs / frameDurationMs_; } } else if (forceVoiceActiveFramesLeft > 0) { // if we didn't detect voice, but we haven't elapsed the minimum duration, // force voice to be true newVoice = true; forceVoiceActiveFramesLeft -= 1; consecutiveActiveFrames += 1; } else { // else no voice and no need to force newVoice = false; consecutiveActiveFrames = 0; } return newVoice; } private: void enqueue(AudioFrameResizer& frameResizer, std::shared_ptr<AudioFrame>&& buf) { if (buf->getFormat() != format_) { frameResizer.enqueue(resampler_->resample(std::move(buf), format_)); } else frameResizer.enqueue(std::move(buf)); }; }; } // namespace jami
6,498
C++
.h
162
33.277778
131
0.660117
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
752,005
message_channel_handler.h
savoirfairelinux_jami-daemon/src/jamidht/message_channel_handler.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 "jamidht/channel_handler.h" #include "jamidht/jamiaccount.h" #include <dhtnet/connectionmanager.h> namespace jami { /** * Manages channels for exchanging messages between peers */ class MessageChannelHandler : public ChannelHandlerInterface { public: MessageChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm); ~MessageChannelHandler(); /** * Ask for a new message channel * @param deviceId The device to connect * @param name (Unused, generated from deviceId) * @param cb The callback to call when connected (can be immediate if already connected) */ void connect(const DeviceId& deviceId, const std::string&, ConnectCb&& cb) override; std::shared_ptr<dhtnet::ChannelSocket> getChannel(const std::string& peer, const DeviceId& deviceId) const; std::vector<std::shared_ptr<dhtnet::ChannelSocket>> getChannels(const std::string& peer) const; /** * Determine if we accept or not the message request * @param deviceId Device who asked * @param name Name asked * @return if the channel is for a valid conversation and device not banned */ bool onRequest(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name) override; /** * Launch message process * @param deviceId Device who asked * @param name Name asked * @param channel Channel used to message */ void onReady(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) override; struct Message { std::string t; /* Message type */ std::string c; /* Message content */ std::unique_ptr<ConversationRequest> req; /* Conversation request */ MSGPACK_DEFINE_MAP(t, c, req) }; static bool sendMessage(const std::shared_ptr<dhtnet::ChannelSocket>&, const Message& message); private: struct Impl; std::shared_ptr<Impl> pimpl_; }; } // namespace jami
2,906
C++
.h
66
39.575758
111
0.678799
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
752,006
typers.h
savoirfairelinux_jami-daemon/src/jamidht/typers.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 <asio.hpp> #include <map> #include <memory> #include <set> #include <string> namespace jami { class JamiAccount; class Typers: public std::enable_shared_from_this<Typers> { public: Typers(const std::shared_ptr<JamiAccount>& acc, const std::string &convId); ~Typers(); /** * Add typer to the list of typers * @param typer * @param sendMessage (should be true for local typer, false for remote typer) */ void addTyper(const std::string &typer, bool sendMessage = false); void removeTyper(const std::string &typer, bool sendMessage = false); private: void onTyperTimeout(const asio::error_code& ec, const std::string &typer); std::shared_ptr<asio::io_context> ioContext_; std::map<std::string, asio::steady_timer> watcher_; std::weak_ptr<JamiAccount> acc_; std::string accountId_; std::string convId_; std::string selfUri_; }; } // namespace jami
1,660
C++
.h
46
33.086957
82
0.722118
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
752,007
accountarchive.h
savoirfairelinux_jami-daemon/src/jamidht/accountarchive.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 "jami_contact.h" #include "jamidht/jamiaccount.h" #include "fileutils.h" #include <opendht/crypto.h> #include <memory> #include <vector> #include <map> #include <string> namespace jami { /** * Crypto material contained in the archive, * not persisted in the account configuration */ struct AccountArchive { /** Account main private key and certificate chain */ dht::crypto::Identity id; /** Generated CA key (for self-signed certificates) */ std::shared_ptr<dht::crypto::PrivateKey> ca_key; /** Revoked devices */ std::shared_ptr<dht::crypto::RevocationList> revoked; /** Ethereum private key */ std::vector<uint8_t> eth_key; /** Contacts */ std::map<dht::InfoHash, Contact> contacts; // Conversations std::map<std::string, ConvInfo> conversations; std::map<std::string, ConversationRequest> conversationsRequests; /** Account configuration */ std::map<std::string, std::string> config; /** Salt for the archive encryption password. */ std::vector<uint8_t> password_salt; AccountArchive() = default; AccountArchive(const std::vector<uint8_t>& data, const std::vector<uint8_t>& password_salt = {}) { deserialize(data, password_salt); } AccountArchive(const std::filesystem::path& path, std::string_view scheme = {}, const std::string& pwd = {}) { load(path, scheme, pwd); } /** Serialize structured archive data to memory. */ std::string serialize() const; /** Deserialize archive from memory. */ void deserialize(const std::vector<uint8_t>& data, const std::vector<uint8_t>& salt); /** Load archive from file, optionally encrypted with provided password. */ void load(const std::filesystem::path& path, std::string_view scheme, const std::string& pwd) { auto data = fileutils::readArchive(path, scheme, pwd); deserialize(data.data, data.salt); } /** Save archive to file, optionally encrypted with provided password. */ void save(const std::filesystem::path& path, std::string_view scheme, const std::string& password) const { fileutils::writeArchive(serialize(), path, scheme, password, password_salt); } }; } // namespace jami
2,933
C++
.h
67
40.104478
141
0.710425
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
752,008
sync_channel_handler.h
savoirfairelinux_jami-daemon/src/jamidht/sync_channel_handler.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 "jamidht/channel_handler.h" #include "jamidht/jamiaccount.h" #include <dhtnet/connectionmanager.h> namespace jami { /** * Manages channels for syncing information between devices of the same account */ class SyncChannelHandler : public ChannelHandlerInterface { public: SyncChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm); ~SyncChannelHandler(); /** * Ask for a new sync channel * @param deviceId The device to connect * @param name (Unused, generated from deviceId) * @param cb The callback to call when connected (can be immediate if already connected) */ void connect(const DeviceId& deviceId, const std::string&, ConnectCb&& cb) override; /** * Determine if we accept or not the sync request * @param deviceId Device who asked * @param name Name asked * @return if the channel is for a valid conversation and device not banned */ bool onRequest(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name) override; /** * Launch sync process * @param deviceId Device who asked * @param name Name asked * @param channel Channel used to sync */ void onReady(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) override; private: std::weak_ptr<JamiAccount> account_; dhtnet::ConnectionManager& connectionManager_; }; } // namespace jami
2,328
C++
.h
57
36.807018
108
0.701413
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
752,009
configkeys.h
savoirfairelinux_jami-daemon/src/jamidht/configkeys.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 jami { namespace Conf { constexpr const char* const DHT_PORT_KEY = "dhtPort"; constexpr const char* const DHT_VALUES_PATH_KEY = "dhtValuesPath"; constexpr const char* const DHT_CONTACTS = "dhtContacts"; constexpr const char* const DHT_PUBLIC_PROFILE = "dhtPublicProfile"; constexpr const char* const DHT_PUBLIC_IN_CALLS = "dhtPublicInCalls"; constexpr const char* const DHT_ALLOW_PEERS_FROM_HISTORY = "allowPeersFromHistory"; constexpr const char* const DHT_ALLOW_PEERS_FROM_CONTACT = "allowPeersFromContact"; constexpr const char* const DHT_ALLOW_PEERS_FROM_TRUSTED = "allowPeersFromTrusted"; constexpr const char* const ETH_KEY = "ethKey"; constexpr const char* const ETH_PATH = "ethPath"; constexpr const char* const ETH_ACCOUNT = "ethAccount"; constexpr const char* const RING_CA_KEY = "ringCaKey"; constexpr const char* const RING_ACCOUNT_KEY = "ringAccountKey"; constexpr const char* const RING_ACCOUNT_CERT = "ringAccountCert"; constexpr const char* const RING_ACCOUNT_RECEIPT = "ringAccountReceipt"; constexpr const char* const RING_ACCOUNT_RECEIPT_SIG = "ringAccountReceiptSignature"; constexpr const char* const RING_ACCOUNT_CRL = "ringAccountCRL"; constexpr const char* const RING_ACCOUNT_CONTACTS = "ringAccountContacts"; constexpr const char* const CONVERSATIONS_KEY = "conversations"; constexpr const char* const CONVERSATIONS_REQUESTS_KEY = "conversationsRequests"; constexpr const char* const PROXY_ENABLED_KEY = "proxyEnabled"; constexpr const char* const PROXY_SERVER_KEY = "proxyServer"; } // namespace Conf } // namespace jami
2,291
C++
.h
43
51.837209
85
0.782977
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
752,010
conversation_module.h
savoirfairelinux_jami-daemon/src/jamidht/conversation_module.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 "scheduled_executor.h" #include "jamidht/account_manager.h" #include "jamidht/conversation.h" #include "jamidht/conversationrepository.h" #include "jamidht/jami_contact.h" #include <mutex> #include <msgpack.hpp> namespace jami { static constexpr const char MIME_TYPE_INVITE[] {"application/invite"}; static constexpr const char MIME_TYPE_GIT[] {"application/im-gitmessage-id"}; class SIPCall; struct SyncMsg { DeviceSync ds; std::map<std::string, ConvInfo> c; std::map<std::string, ConversationRequest> cr; // p is conversation's preferences. It's not stored in c, as // we can update the preferences without touching any confInfo. std::map<std::string, std::map<std::string, std::string>> p; // Last displayed messages [[deprecated]] std::map<std::string, std::map<std::string, std::string>> ld; // Read & fetched status /* * {{ convId, * { memberUri,, { * {"fetch", "commitId"}, * {"fetched_ts", "timestamp"}, * {"read", "commitId"}, * {"read_ts", "timestamp"} * } * }} */ std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> ms; MSGPACK_DEFINE(ds, c, cr, p, ld, ms) }; using ChannelCb = std::function<bool(const std::shared_ptr<dhtnet::ChannelSocket>&)>; using NeedSocketCb = std::function<void(const std::string&, const std::string&, ChannelCb&&, const std::string&)>; using SengMsgCb = std::function< uint64_t(const std::string&, const DeviceId&, std::map<std::string, std::string>, uint64_t)>; using NeedsSyncingCb = std::function<void(std::shared_ptr<SyncMsg>&&)>; using OneToOneRecvCb = std::function<void(const std::string&, const std::string&)>; class ConversationModule { public: ConversationModule(std::shared_ptr<JamiAccount> account, std::shared_ptr<AccountManager> accountManager, NeedsSyncingCb&& needsSyncingCb, SengMsgCb&& sendMsgCb, NeedSocketCb&& onNeedSocket, NeedSocketCb&& onNeedSwarmSocket, OneToOneRecvCb&& oneToOneRecvCb, bool autoLoadConversations = true); ~ConversationModule() = default; void setAccountManager(std::shared_ptr<AccountManager> accountManager); /** * Refresh information about conversations */ void loadConversations(); void loadSingleConversation(const std::string& convId); #ifdef LIBJAMI_TESTABLE void onBootstrapStatus(const std::function<void(std::string, Conversation::BootstrapStatus)>& cb); #endif void monitor(); /** * Bootstrap swarm managers to other peers */ void bootstrap(const std::string& convId = ""); /** * Clear not removed fetch */ void clearPendingFetch(); /** * Reload requests from file */ void reloadRequests(); /** * Return all conversation's id (including syncing ones) */ std::vector<std::string> getConversations() const; /** * Get related conversation with member * @param uri The member to search for * @return the conversation id if found else empty */ std::string getOneToOneConversation(const std::string& uri) const noexcept; /** * Replace linked conversation in contact's details * @param uri Of the contact * @param oldConv Current conversation * @param newConv * @return if replaced */ bool updateConvForContact(const std::string& uri, const std::string& oldConv, const std::string& newConv); /** * Return conversation's requests */ std::vector<std::map<std::string, std::string>> getConversationRequests() const; /** * Called when detecting a new trust request with linked one to one * @param uri Sender's URI * @param conversationId Related conversation's id * @param payload VCard * @param received Received time */ void onTrustRequest(const std::string& uri, const std::string& conversationId, const std::vector<uint8_t>& payload, time_t received); /** * Called when receiving a new conversation's request * @param from Sender * @param value Conversation's request */ void onConversationRequest(const std::string& from, const Json::Value& value); /** * Retrieve author of a conversation request * @param convId Conversation's id * @return the author of the conversation request */ std::string peerFromConversationRequest(const std::string& convId) const; /** * Called when a peer needs an invite for a conversation (generally after that they received * a commit notification for a conversation they don't have yet) * @param from * @param conversationId */ void onNeedConversationRequest(const std::string& from, const std::string& conversationId); /** * Accept a conversation's request * @param convId * @param deviceId If a trust request is accepted from a device (can help to sync) */ void acceptConversationRequest(const std::string& conversationId, const std::string& deviceId = ""); /** * Decline a conversation's request * @param convId */ void declineConversationRequest(const std::string& conversationId); /** * Clone conversation from a member * @note used to clone an old conversation after deleting/re-adding a contact * @param conversationId * @param uri * @param oldConvId */ void cloneConversationFrom(const std::string& conversationId, const std::string& uri, const std::string& oldConvId = ""); /** * Starts a new conversation * @param mode Wanted mode * @param otherMember If needed (one to one) * @return conversation's id */ std::string startConversation(ConversationMode mode = ConversationMode::INVITES_ONLY, const dht::InfoHash& otherMember = {}); // 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 reactToMessage(const std::string& conversationId, const std::string& newBody, const std::string& reactToId); /** * Add to the related conversation the call history message * @param uri Peer number * @param duration_ms The call duration in ms * @param reason */ void addCallHistoryMessage(const std::string& uri, uint64_t duration_ms, const std::string& reason); // Received that a peer displayed a message bool onMessageDisplayed(const std::string& peer, const std::string& conversationId, const std::string& interactionId); std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> convMessageStatus() const; /** * Load conversation's messages * @param conversationId Conversation to load * @param fromMessage * @param n Max interactions to load * @return id of the operation */ uint32_t loadConversationMessages(const std::string& conversationId, const std::string& fromMessage = "", size_t n = 0); uint32_t loadConversation(const std::string& conversationId, const std::string& fromMessage = "", size_t n = 0); uint32_t loadConversationUntil(const std::string& conversationId, const std::string& fromMessage, const std::string& to); uint32_t loadSwarmUntil(const std::string& conversationId, const std::string& fromMessage, const std::string& toMessage); /** * Clear loaded interactions * @param conversationId */ void clearCache(const std::string& conversationId); // File transfer /** * Returns related transfer manager * @param id Conversation's id * @return nullptr if not found, else the manager */ std::shared_ptr<TransferManager> dataTransfer(const std::string& id) const; /** * Choose if we can accept channel request * @param member Member to check * @param fileId File transfer to check (needs to be waiting) * @param verifyShaSum For debug only * @return if we accept the channel request */ bool onFileChannelRequest(const std::string& conversationId, const std::string& member, const std::string& fileId, bool verifyShaSum = true) const; /** * Ask conversation's members to send a file to this device * @param conversationId Related conversation * @param interactionId Related interaction * @param fileId Related fileId * @param path where to download the file */ bool downloadFile(const std::string& conversationId, const std::string& interactionId, const std::string& fileId, const std::string& path, size_t start = 0, size_t end = 0); // Sync /** * Sync conversations with detected peer */ void syncConversations(const std::string& peer, const std::string& deviceId); /** * Detect new conversations and request from other devices * @param msg Received data * @param peerId Sender * @param deviceId */ void onSyncData(const SyncMsg& msg, const std::string& peerId, const std::string& deviceId); /** * Check if we need to share infos with a contact * @param memberUri * @param deviceId */ bool needsSyncingWith(const std::string& memberUri, const std::string& deviceId) const; /** * Notify that a peer fetched a commit * @note: this definitely remove the repository when needed (when we left and someone fetched * the information) * @param conversationId Related conv * @param deviceId Device who synced * @param commit HEAD synced */ void setFetched(const std::string& conversationId, const std::string& deviceId, const std::string& commit); /** * Launch fetch on new commit * @param peer Who sent the notification * @param deviceId Who sent the notification * @param conversationId Related conversation * @param commitId Commit to retrieve */ void fetchNewCommits(const std::string& peer, const std::string& deviceId, const std::string& conversationId, const std::string& commitId); // Conversation's member /** * Adds a new member to a conversation (this will triggers a member event + new message on success) * @param conversationId * @param contactUri * @param sendRequest If we need to inform the peer (used for tests) */ void addConversationMember(const std::string& conversationId, const dht::InfoHash& contactUri, bool sendRequest = true); /** * Remove a member from a conversation (this will trigger a member event + new message on success) * @param conversationId * @param contactUri * @param isDevice */ void removeConversationMember(const std::string& conversationId, const dht::InfoHash& contactUri, bool isDevice = false); /** * 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; /** * Retrieve the number of interactions from interactionId to HEAD * @param convId * @param interactionId "" for getting the whole history * @param authorUri Stop when detect author * @return number of interactions since interactionId */ uint32_t countInteractions(const std::string& convId, const std::string& toId, const std::string& fromId, const std::string& authorUri) const; /** * Search in conversations via a filter * @param req Id of the request * @param convId Leave empty to search in all conversation, else add the conversation's id * @param filter Parameters for the search * @note triggers messagesFound */ void search(uint32_t req, const std::string& convId, const Filter& filter) const; // Conversation's infos management /** * Update metadatas from conversations (like title, avatar, etc) * @param conversationId * @param infos * @param sync If we need to sync with others (used for tests) */ void updateConversationInfos(const std::string& conversationId, const std::map<std::string, std::string>& infos, bool sync = true); std::map<std::string, std::string> conversationInfos(const std::string& conversationId) const; /** * Update user's preferences (like color, notifications, etc) to be synced across devices * @param conversationId * @param preferences */ void setConversationPreferences(const std::string& conversationId, const std::map<std::string, std::string>& prefs); std::map<std::string, std::string> getConversationPreferences(const std::string& conversationId, bool includeCreated = false) const; /** * Retrieve all conversation preferences to sync with other devices */ std::map<std::string, std::map<std::string, std::string>> convPreferences() const; // Get the map into a VCard format for storing std::vector<uint8_t> conversationVCard(const std::string& conversationId) const; /** * Return if a device or member is banned from a conversation * @param convId * @param uri */ bool isBanned(const std::string& convId, const std::string& uri) const; // Remove swarm /** * Remove one to one conversations related to a contact * @param uri Of the contact * @param ban If banned */ void removeContact(const std::string& uri, bool ban); /** * Remove a conversation, but not the contact * @param conversationId * @return if successfully removed */ bool removeConversation(const std::string& conversationId); void initReplay(const std::string& oldConvId, const std::string& newConvId); /** * Check if we're hosting a specific conference * @param conversationId (empty to search all conv) * @param confId * @return true if hosting this conference */ bool isHosting(const std::string& conversationId, const std::string& confId) const; /** * Return active calls * @param convId Which conversation to choose * @return {{"id":id}, {"uri":uri}, {"device":device}} */ std::vector<std::map<std::string, std::string>> getActiveCalls( const std::string& conversationId) const; /** * Call the conversation * @param url Url to call (swarm:conversation or swarm:conv/account/device/conf to join) * @param mediaList The media list * @param cb Callback to pass which device to call (called in the same thread) * @return call if a call is started, else nullptr */ std::shared_ptr<SIPCall> 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); void hostConference(const std::string& conversationId, const std::string& confId, const std::string& callId, const std::vector<libjami::MediaMap>& mediaList = {}); // The following methods modify what is stored on the disk static void saveConvInfos(const std::string& accountId, const std::map<std::string, ConvInfo>& conversations); static void saveConvInfosToPath(const std::filesystem::path& path, const std::map<std::string, ConvInfo>& conversations); static void saveConvRequests( const std::string& accountId, const std::map<std::string, ConversationRequest>& conversationsRequests); static void saveConvRequestsToPath( const std::filesystem::path& path, const std::map<std::string, ConversationRequest>& conversationsRequests); static std::map<std::string, ConvInfo> convInfos(const std::string& accountId); static std::map<std::string, ConvInfo> convInfosFromPath(const std::filesystem::path& path); static std::map<std::string, ConversationRequest> convRequests(const std::string& accountId); static std::map<std::string, ConversationRequest> convRequestsFromPath( const std::filesystem::path& path); void addConvInfo(const ConvInfo& info); /** * Get a conversation * @param convId */ std::shared_ptr<Conversation> getConversation(const std::string& convId); /** * Return current git socket used for a conversation * @param deviceId Related device * @param conversationId Related conversation * @return the related socket */ std::shared_ptr<dhtnet::ChannelSocket> gitSocket(std::string_view deviceId, std::string_view convId) const; void removeGitSocket(std::string_view deviceId, std::string_view convId); void addGitSocket(std::string_view deviceId, std::string_view convId, const std::shared_ptr<dhtnet::ChannelSocket>& channel); /** * Clear all connection (swarm channels) */ void shutdownConnections(); /** * Add a swarm connection * @param conversationId * @param socket */ void addSwarmChannel(const std::string& conversationId, std::shared_ptr<dhtnet::ChannelSocket> socket); /** * Triggers a bucket maintainance for DRTs */ void connectivityChanged(); /** * Get Typers object for a conversation * @param convId * @return the Typer object */ std::shared_ptr<Typers> getTypers(const std::string& convId); private: class Impl; std::shared_ptr<Impl> pimpl_; }; } // namespace jami
20,868
C++
.h
484
34.157025
128
0.616595
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
752,011
channeled_transport.h
savoirfairelinux_jami-daemon/src/jamidht/channeled_transport.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 "noncopyable.h" #include "scheduled_executor.h" #include "jamidht/abstract_sip_transport.h" #include <dhtnet/multiplexed_socket.h> #include <atomic> #include <condition_variable> #include <chrono> #include <list> #include <memory> #include <thread> #include <type_traits> #include <utility> namespace jami { using onShutdownCb = std::function<void(void)>; namespace tls { /** * ChanneledSIPTransport * * Implements a pjsip_transport on top of a ChannelSocket */ class ChanneledSIPTransport : public AbstractSIPTransport { public: ChanneledSIPTransport(pjsip_endpoint* endpt, const std::shared_ptr<dhtnet::ChannelSocket>& socket, onShutdownCb&& cb); ~ChanneledSIPTransport(); /** * Connect callbacks for channeled socket, must be done when the channel is ready to be used */ void start(); pjsip_transport* getTransportBase() override { return &trData_.base; } dhtnet::IpAddr getLocalAddress() const override { return local_; } private: NON_COPYABLE(ChanneledSIPTransport); // The SIP transport uses a ChannelSocket to send and receive datas std::shared_ptr<dhtnet::ChannelSocket> socket_ {}; onShutdownCb shutdownCb_ {}; dhtnet::IpAddr local_ {}; dhtnet::IpAddr remote_ {}; // PJSIP transport backend TransportData trData_ {}; // uplink to "this" (used by PJSIP called C-callbacks) std::unique_ptr<pj_pool_t, decltype(pj_pool_release)*> pool_; std::unique_ptr<pj_pool_t, decltype(pj_pool_release)*> rxPool_; pjsip_rx_data rdata_ {}; pj_status_t send(pjsip_tx_data*, const pj_sockaddr_t*, int, void*, pjsip_transport_callback); // Handle disconnected event std::atomic_bool disconnected_ {false}; }; } // namespace tls } // namespace jami
2,539
C++
.h
68
33.720588
97
0.721271
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
752,012
gitserver.h
savoirfairelinux_jami-daemon/src/jamidht/gitserver.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 <functional> #include <memory> #include <string> #include "def.h" #include "jamidht/conversationrepository.h" namespace dhtnet { class ChannelSocket; } namespace jami { using onFetchedCb = std::function<void(const std::string&)>; /** * This class offers to a ChannelSocket the possibility to interact with a Git repository */ class LIBJAMI_TESTABLE GitServer { public: /** * Serve a conversation to a remote client * This client will be able to fetch commits/clone the repository * @param accountId Account related to the conversation * @param conversationId Conversation's id * @param client The client to serve */ GitServer(const std::string& accountId, const std::string& conversationId, const std::shared_ptr<dhtnet::ChannelSocket>& client); ~GitServer(); /** * Add a callback which will be triggered when the peer gets the data * @param cb */ void setOnFetched(const onFetchedCb& cb); /** * Stopping a GitServer will shut the channel down */ void stop(); private: class Impl; std::unique_ptr<Impl> pimpl_; }; } // namespace jami
1,925
C++
.h
58
29.689655
89
0.709903
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
752,013
contact_list.h
savoirfairelinux_jami-daemon/src/jamidht/contact_list.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 "jami_contact.h" #include <dhtnet/certstore.h> #include <opendht/infohash.h> #include <opendht/crypto.h> #include <map> #include <mutex> #include <chrono> namespace jami { class ContactList { public: using clock = std::chrono::system_clock; using time_point = clock::time_point; using VerifyResult = dht::crypto::TrustList::VerifyResult; using OnContactAdded = std::function<void(const std::string&, bool)>; using OnContactRemoved = std::function<void(const std::string&, bool)>; using OnIncomingTrustRequest = std::function< void(const std::string&, const std::string&, const std::vector<uint8_t>&, time_t)>; using OnAcceptConversation = std::function<void(const std::string&, const std::string&)>; using OnConfirmation = std::function<void(const std::string&, const std::string&)>; using OnDevicesChanged = std::function<void(const std::map<dht::PkId, KnownDevice>&)>; struct OnChangeCallback { OnContactAdded contactAdded; OnContactRemoved contactRemoved; OnIncomingTrustRequest trustRequest; OnDevicesChanged devicesChanged; OnAcceptConversation acceptConversation; OnConfirmation onConfirmation; }; ContactList(const std::string& accountId, const std::shared_ptr<crypto::Certificate>& cert, const std::filesystem::path& path, OnChangeCallback cb); ~ContactList(); const std::string& accountId() const { return accountId_; } void load(); void save(); /* Contacts */ std::map<std::string, std::string> getContactDetails(const dht::InfoHash&) const; bool removeContact(const dht::InfoHash&, bool ban); bool removeContactConversation(const dht::InfoHash&); bool addContact(const dht::InfoHash&, bool confirmed = false, const std::string& conversationId = ""); void updateConversation(const dht::InfoHash& h, const std::string& conversationId); bool setCertificateStatus(const std::string& cert_id, const dhtnet::tls::TrustStore::PermissionStatus status); bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert, dhtnet::tls::TrustStore::PermissionStatus status, bool local = true); dhtnet::tls::TrustStore::PermissionStatus getCertificateStatus(const std::string& cert_id) const { return trust_->getCertificateStatus(cert_id); } std::vector<std::string> getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status) const { return trust_->getCertificatesByStatus(status); } bool isAllowed(const crypto::Certificate& crt, bool allowPublic) { return trust_->isAllowed(crt, allowPublic); } VerifyResult isValidAccountDevice(const crypto::Certificate& crt) const { return accountTrust_.verify(crt); } const std::map<dht::InfoHash, Contact>& getContacts() const; void setContacts(const std::map<dht::InfoHash, Contact>&); void updateContact(const dht::InfoHash&, const Contact&, bool emit = true); /** Should be called only after updateContact */ void saveContacts() const; const std::filesystem::path& path() const { return path_; } /* Contact requests */ /** Inform of a new contact request. Returns true if the request should be immediatly accepted * (already a contact) */ bool 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); std::vector<std::map<std::string, std::string>> getTrustRequests() const; std::map<std::string, std::string> getTrustRequest(const dht::InfoHash& from) const; void acceptConversation(const std::string& convId, const std::string& deviceId = ""); // ToDO this is a bit dirty imho bool acceptTrustRequest(const dht::InfoHash& from); bool discardTrustRequest(const dht::InfoHash& from); /* Devices */ const std::map<dht::PkId, KnownDevice>& getKnownDevices() const { return knownDevices_; } void foundAccountDevice(const dht::PkId& device, const std::string& name = {}, const time_point& last_sync = time_point::min()); bool foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, const std::string& name = {}, const time_point& last_sync = time_point::min()); bool removeAccountDevice(const dht::PkId& device); void setAccountDeviceName(const dht::PkId& device, const std::string& name); std::string getAccountDeviceName(const dht::PkId& device) const; DeviceSync getSyncData() const; bool syncDevice(const dht::PkId& device, const time_point& syncDate); private: mutable std::mutex mutex_; std::map<dht::InfoHash, Contact> contacts_; std::map<dht::InfoHash, TrustRequest> trustRequests_; std::map<dht::InfoHash, KnownDevice> knownDevicesLegacy_; std::map<dht::PkId, KnownDevice> knownDevices_; // Trust store with account main certificate as the only CA dht::crypto::TrustList accountTrust_; // Trust store for to match peer certificates std::unique_ptr<dhtnet::tls::TrustStore> trust_; std::filesystem::path path_; std::string accountUri_; OnChangeCallback callbacks_; std::string accountId_; void loadContacts(); void loadTrustRequests(); void loadKnownDevices(); void saveKnownDevices() const; /** Should be called only after onTrustRequest */ void saveTrustRequests() const; }; } // namespace jami
6,625
C++
.h
139
40.431655
122
0.681438
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
752,014
abstract_sip_transport.h
savoirfairelinux_jami-daemon/src/jamidht/abstract_sip_transport.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 <dhtnet/ip_utils.h> #include "connectivity/sip_utils.h" #include <pjsip.h> #include <pj/pool.h> namespace jami { namespace tls { /** * AbstractSIPTransport * * Implements a pjsip_transport on top */ class AbstractSIPTransport { public: struct TransportData { pjsip_transport base; // do not move, SHOULD be the fist member AbstractSIPTransport* self {nullptr}; }; static_assert(std::is_standard_layout<TransportData>::value, "TransportData requires standard-layout"); virtual ~AbstractSIPTransport() {}; virtual pjsip_transport* getTransportBase() = 0; virtual dhtnet::IpAddr getLocalAddress() const = 0; }; } // namespace tls } // namespace jami
1,461
C++
.h
44
30.159091
73
0.730114
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
752,015
conversationrepository.h
savoirfairelinux_jami-daemon/src/jamidht/conversationrepository.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 <optional> #include <git2.h> #include <memory> #include <opendht/default_types.h> #include <string> #include <vector> #include "def.h" using GitPackBuilder = std::unique_ptr<git_packbuilder, decltype(&git_packbuilder_free)>; using GitRepository = std::unique_ptr<git_repository, decltype(&git_repository_free)>; using GitRevWalker = std::unique_ptr<git_revwalk, decltype(&git_revwalk_free)>; using GitCommit = std::unique_ptr<git_commit, decltype(&git_commit_free)>; using GitAnnotatedCommit = std::unique_ptr<git_annotated_commit, decltype(&git_annotated_commit_free)>; using GitIndex = std::unique_ptr<git_index, decltype(&git_index_free)>; using GitTree = std::unique_ptr<git_tree, decltype(&git_tree_free)>; using GitRemote = std::unique_ptr<git_remote, decltype(&git_remote_free)>; using GitReference = std::unique_ptr<git_reference, decltype(&git_reference_free)>; using GitSignature = std::unique_ptr<git_signature, decltype(&git_signature_free)>; using GitObject = std::unique_ptr<git_object, decltype(&git_object_free)>; using GitDiff = std::unique_ptr<git_diff, decltype(&git_diff_free)>; using GitDiffStats = std::unique_ptr<git_diff_stats, decltype(&git_diff_stats_free)>; using GitIndexConflictIterator = std::unique_ptr<git_index_conflict_iterator, decltype(&git_index_conflict_iterator_free)>; namespace jami { using DeviceId = dht::PkId; constexpr auto EFETCH = 1; constexpr auto EINVALIDMODE = 2; constexpr auto EVALIDFETCH = 3; constexpr auto EUNAUTHORIZED = 4; constexpr auto ECOMMIT = 5; class JamiAccount; struct LogOptions { std::string from {}; std::string to {}; uint64_t nbOfCommits {0}; // maximum number of commits wanted bool skipMerge {false}; // Do not include merge commits in the log. Used by the module to get // last interaction without potential merges bool includeTo {false}; // If we want or not the "to" commit [from-to] or [from-to) bool fastLog {false}; // Do not parse content, used mostly to count bool logIfNotFound {true}; // Add a warning in the log if commit is not found std::string authorUri {}; // filter commits from author }; struct Filter { std::string author; std::string lastId; std::string regexSearch; std::string type; int64_t after {0}; int64_t before {0}; uint32_t maxResult {0}; bool caseSensitive {false}; }; struct GitAuthor { std::string name {}; std::string email {}; }; enum class ConversationMode : int { ONE_TO_ONE = 0, ADMIN_INVITES_ONLY, INVITES_ONLY, PUBLIC }; struct ConversationCommit { std::string id {}; std::vector<std::string> parents {}; GitAuthor author {}; std::vector<uint8_t> signed_content {}; std::vector<uint8_t> signature {}; std::string commit_msg {}; std::string linearized_parent {}; int64_t timestamp {0}; }; enum class MemberRole { ADMIN = 0, MEMBER, INVITED, BANNED, LEFT }; struct ConversationMember { std::string uri; MemberRole role; std::map<std::string, std::string> map() const { std::string rolestr; if (role == MemberRole::ADMIN) { rolestr = "admin"; } else if (role == MemberRole::MEMBER) { rolestr = "member"; } else if (role == MemberRole::INVITED) { rolestr = "invited"; } else if (role == MemberRole::BANNED) { rolestr = "banned"; } else if (role == MemberRole::LEFT) { rolestr = "left"; // For one to one } return {{"uri", uri}, {"role", rolestr}}; } MSGPACK_DEFINE(uri, role) }; enum class CallbackResult { Skip, Break, Ok }; using PreConditionCb = std::function<CallbackResult(const std::string&, const GitAuthor&, const GitCommit&)>; using PostConditionCb = std::function<bool(const std::string&, const GitAuthor&, ConversationCommit&)>; using OnMembersChanged = std::function<void(const std::set<std::string>&)>; /** * This class gives access to the git repository that represents the conversation */ class LIBJAMI_TESTABLE ConversationRepository { public: #ifdef LIBJAMI_TESTABLE static bool DISABLE_RESET; // Some tests inject bad files so resetHard() will break the test #endif /** * Creates a new repository, with initial files, where the first commit hash is the conversation id * @param account The related account * @param mode The wanted mode * @param otherMember The other uri * @return the conversation repository object */ static LIBJAMI_TESTABLE std::unique_ptr<ConversationRepository> createConversation( const std::shared_ptr<JamiAccount>& account, ConversationMode mode = ConversationMode::INVITES_ONLY, const std::string& otherMember = ""); /** * Clones a conversation on a remote device * @note This will use the socket registered for the conversation with JamiAccount::addGitSocket() * @param account The account getting the conversation * @param deviceId Remote device * @param conversationId Conversation to clone * @param checkCommitCb Used if commits should be treated */ static LIBJAMI_TESTABLE std::unique_ptr<ConversationRepository> cloneConversation( const std::shared_ptr<JamiAccount>& account, const std::string& deviceId, const std::string& conversationId, std::function<void(std::vector<ConversationCommit>)>&& checkCommitCb = {}); /** * Open a conversation repository for an account and an id * @param account The related account * @param id The conversation id */ ConversationRepository(const std::shared_ptr<JamiAccount>& account, const std::string& id); ~ConversationRepository(); /** * Write the certificate in /members and commit the change * @param uri Member to add * @return the commit id if successful */ std::string addMember(const std::string& uri); /** * Fetch a remote repository via the given socket * @note This will use the socket registered for the conversation with JamiAccount::addGitSocket() * @note will create a remote identified by the deviceId * @param remoteDeviceId Remote device id to fetch * @return if the operation was successful */ bool fetch(const std::string& remoteDeviceId); /** * Retrieve remote head. Can be useful after a fetch operation * @param remoteDeviceId The remote name * @param branch Remote branch to check (default: main) * @return the commit id pointed */ std::string remoteHead(const std::string& remoteDeviceId, const std::string& branch = "main") const; /** * Return the conversation id */ const std::string& id() const; /** * Add a new commit to the conversation * @param msg The commit message of the commit * @param verifyDevice If we need to validate that certificates are correct (used for testing) * @return <empty> on failure, else the message id */ std::string commitMessage(const std::string& msg, bool verifyDevice = true); std::vector<std::string> commitMessages(const std::vector<std::string>& msgs); /** * Amend a commit message * @param id The commit to amend * @param msg The commit message of the commit * @return <empty> on failure, else the message id */ std::string amend(const std::string& id, const std::string& msg); /** * Get commits depending on the options we pass * @return a list of commits */ std::vector<ConversationCommit> log(const LogOptions& options = {}) const; void log(PreConditionCb&& preCondition, std::function<void(ConversationCommit&&)>&& emplaceCb, PostConditionCb&& postCondition, const std::string& from = "", bool logIfNotFound = true) const; std::optional<ConversationCommit> getCommit(const std::string& commitId, bool logIfNotFound = true) const; /** * Get parent via topological + date sort in branch main of a commit * @param commitId id to choice */ std::optional<std::string> linearizedParent(const std::string& commitId) const; /** * Merge another branch into the main branch * @param merge_id The reference to merge * @param force Should be false, skip validateDevice() ; used for test purpose * @return a pair containing if the merge was successful and the merge commit id * generated if one (can be a fast forward merge without commit) */ std::pair<bool, std::string> merge(const std::string& merge_id, bool force = false); /** * Get the common parent between two branches * @param from The first branch * @param to The second branch * @return the common parent */ std::string mergeBase(const std::string& from, const std::string& to) const; /** * Get current diff stats between two commits * @param oldId Old commit * @param newId Recent commit (empty value will compare to the empty repository) * @note "HEAD" is also accepted as parameter for newId * @return diff stats */ std::string diffStats(const std::string& newId, const std::string& oldId = "") const; /** * Get changed files from a git diff * @param diffStats The stats to analyze * @return get the changed files from a git diff */ static std::vector<std::string> changedFiles(std::string_view diffStats); /** * Join a repository * @return commit Id */ std::string join(); /** * Erase self from repository * @return commit Id */ std::string leave(); /** * Erase repository */ void erase(); /** * Get conversation's mode * @return the mode */ ConversationMode mode() const; /** * The voting system is divided in two parts. The voting phase where * admins can decide an action (such as kicking someone) * and the resolving phase, when > 50% of the admins voted, we can * considered the vote as finished */ /** * Add a vote to kick a device or a user * @param uri identified of the user/device * @param type device, members, admins or invited * @return the commit id or empty if failed */ std::string voteKick(const std::string& uri, const std::string& type); /** * Add a vote to re-add a user * @param uri identified of the user * @param type device, members, admins or invited * @return the commit id or empty if failed */ std::string voteUnban(const std::string& uri, const std::string_view type); /** * Validate if a vote is finished * @param uri identified of the user/device * @param type device, members, admins or invited * @param voteType "ban" or "unban" * @return the commit id or empty if failed */ std::string resolveVote(const std::string& uri, const std::string_view type, const std::string& voteType); /** * Validate a fetch with remote device * @param remotedevice * @return the validated commits and if an error occurs */ std::pair<std::vector<ConversationCommit>, bool> validFetch( const std::string& remoteDevice) const; bool validClone(std::function<void(std::vector<ConversationCommit>)>&& checkCommitCb) const; /** * Delete branch with remote * @param remoteDevice */ void removeBranchWith(const std::string& remoteDevice); /** * One to one util, get initial members * @return initial members */ std::vector<std::string> getInitialMembers() const; /** * Get conversation's members * @return members */ std::vector<ConversationMember> members() const; /** * Get conversation's devices * @param ignoreExpired If we want to ignore expired devices * @return members */ std::map<std::string, std::vector<DeviceId>> devices(bool ignoreExpired = true) const; /** * @param filter If we want to remove one member * @param filteredRoles If we want to ignore some roles * @return members' uris */ std::set<std::string> memberUris(std::string_view filter, const std::set<MemberRole>& filteredRoles) const; /** * To use after a merge with member's events, refresh members knowledge */ void refreshMembers() const; void onMembersChanged(OnMembersChanged&& cb); /** * Because conversations can contains non contacts certificates, this methods * loads certificates in conversations into the cert store * @param blocking if we need to wait that certificates are pinned */ void pinCertificates(bool blocking = false); /** * Retrieve the uri from a deviceId * @note used by swarm manager (peersToSyncWith) * @param deviceId * @return corresponding issuer */ std::string uriFromDevice(const std::string& deviceId) const; /** * Change repository's infos * @param map New infos (supported keys: title, description, avatar) * @return the commit id */ std::string updateInfos(const std::map<std::string, std::string>& map); /** * Retrieve current infos (title, description, avatar, mode) * @return infos */ std::map<std::string, std::string> infos() const; static std::map<std::string, std::string> infosFromVCard( std::map<std::string, std::string>&& details); /** * Convert ConversationCommit to MapStringString for the client */ std::vector<std::map<std::string, std::string>> convCommitsToMap( const std::vector<ConversationCommit>& commits) const; std::optional<std::map<std::string, std::string>> convCommitToMap( const ConversationCommit& commit) const; /** * Get current HEAD hash */ std::string getHead() const; private: ConversationRepository() = delete; class Impl; std::unique_ptr<Impl> pimpl_; }; } // namespace jami MSGPACK_ADD_ENUM(jami::MemberRole);
15,160
C++
.h
378
34.484127
103
0.665196
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
752,016
jami_contact.h
savoirfairelinux_jami-daemon/src/jamidht/jami_contact.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 "string_utils.h" #include <opendht/infohash.h> #include <opendht/value.h> #include <opendht/default_types.h> #include <msgpack.hpp> #include <json/json.h> #include <map> #include <string> #include <ctime> #include <ciso646> namespace jami { struct Contact { /** Time of contact addition */ time_t added {0}; /** Time of contact removal */ time_t removed {0}; /** True if we got confirmation that this contact also added us */ bool confirmed {false}; /** True if the contact is banned (if not active) */ bool banned {false}; /** Non empty if a swarm is linked */ std::string conversationId {}; /** True if the contact is an active contact (not banned nor removed) */ bool isActive() const { return added > removed; } bool isBanned() const { return not isActive() and banned; } Contact() = default; Contact(const Json::Value& json) { added = json["added"].asLargestUInt(); removed = json["removed"].asLargestUInt(); confirmed = json["confirmed"].asBool(); banned = json["banned"].asBool(); conversationId = json["conversationId"].asString(); } /** * Update this contact using other known contact information, * return true if contact state was changed. */ bool update(const Contact& c) { const auto copy = *this; if (c.added > added) { added = c.added; conversationId = c.conversationId; } if (c.removed > removed) { removed = c.removed; banned = c.banned; } if (c.confirmed != confirmed) { confirmed = c.confirmed or confirmed; } if (isActive()) { removed = 0; banned = 0; } if (c.isActive() and conversationId.empty() and not c.conversationId.empty()) { conversationId = c.conversationId; } return hasDifferentState(copy); } bool hasDifferentState(const Contact& other) const { return other.isActive() != isActive() or other.isBanned() != isBanned() or other.confirmed != confirmed; } Json::Value toJson() const { Json::Value json; json["added"] = Json::Int64(added); if (removed) { json["removed"] = Json::Int64(removed); } if (confirmed) json["confirmed"] = confirmed; if (banned) json["banned"] = banned; json["conversationId"] = conversationId; return json; } std::map<std::string, std::string> toMap() const { std::map<std::string, std::string> result {{"added", std::to_string(added)}, {"removed", std::to_string(removed)}, {"conversationId", conversationId}}; if (isActive()) result.emplace("confirmed", confirmed ? TRUE_STR : FALSE_STR); if (isBanned()) result.emplace("banned", TRUE_STR); return result; } MSGPACK_DEFINE_MAP(added, removed, confirmed, banned, conversationId) }; struct TrustRequest { std::shared_ptr<dht::crypto::PublicKey> device; std::string conversationId; time_t received; std::vector<uint8_t> payload; MSGPACK_DEFINE_MAP(device, conversationId, received, payload) }; struct DeviceAnnouncement : public dht::SignedValue<DeviceAnnouncement> { private: using BaseClass = dht::SignedValue<DeviceAnnouncement>; public: static const constexpr dht::ValueType& TYPE = dht::ValueType::USER_DATA; dht::InfoHash dev; std::shared_ptr<dht::crypto::PublicKey> pk; MSGPACK_DEFINE_MAP(dev, pk) }; struct KnownDeviceSync { std::string name; dht::InfoHash sha1; MSGPACK_DEFINE_MAP(name, sha1) }; struct DeviceSync : public dht::EncryptedValue<DeviceSync> { static const constexpr dht::ValueType& TYPE = dht::ValueType::USER_DATA; uint64_t date; std::string device_name; std::map<dht::InfoHash, std::string> devices_known; // Legacy std::map<dht::PkId, KnownDeviceSync> devices; std::map<dht::InfoHash, Contact> peers; std::map<dht::InfoHash, TrustRequest> trust_requests; MSGPACK_DEFINE_MAP(date, device_name, devices_known, devices, peers, trust_requests) }; struct KnownDevice { using clock = std::chrono::system_clock; using time_point = clock::time_point; /** Device certificate */ std::shared_ptr<dht::crypto::Certificate> certificate; /** Device name */ std::string name {}; /** Time of last received device sync */ time_point last_sync {time_point::min()}; KnownDevice(const std::shared_ptr<dht::crypto::Certificate>& cert, const std::string& n = {}, time_point sync = time_point::min()) : certificate(cert) , name(n) , last_sync(sync) {} }; } // namespace jami
5,682
C++
.h
164
28.304878
88
0.63436
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
752,017
server_account_manager.h
savoirfairelinux_jami-daemon/src/jamidht/server_account_manager.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 "account_manager.h" #include <queue> #include <set> #include <chrono> namespace jami { class ServerAccountManager : public AccountManager { public: ServerAccountManager(const std::filesystem::path& path, const std::string& managerHostname, const std::string& nameServer); struct ServerAccountCredentials : AccountCredentials { std::string username; std::shared_ptr<dht::crypto::Certificate> ca; }; void initAuthentication(const std::string& accountId, PrivateKey request, std::string deviceName, std::unique_ptr<AccountCredentials> credentials, AuthSuccessCallback onSuccess, AuthFailureCallback onFailure, const OnChangeCallback& onChange) override; bool changePassword(const std::string& /*password_old*/, const std::string& /*password_new*/) override { return false; } void syncDevices() override; using SyncBlueprintCallback = std::function<void(const std::map<std::string, std::string>& config)>; void syncBlueprintConfig(SyncBlueprintCallback onSuccess); bool revokeDevice(const std::string& device, std::string_view scheme, const std::string& password, RevokeDeviceCallback cb) override; bool searchUser(const std::string& query, SearchCallback cb) override; void registerName(const std::string& name, std::string_view scheme, const std::string& password, RegistrationCallback cb) override; void onNeedsMigration(std::function<void()> cb) { onNeedsMigration_ = std::move(cb); } private: struct AuthContext { std::string accountId; PrivateKey key; CertRequest request; std::string deviceName; std::unique_ptr<ServerAccountCredentials> credentials; AuthSuccessCallback onSuccess; AuthFailureCallback onFailure; }; const std::string managerHostname_; std::shared_ptr<dht::Logger> logger_; std::mutex requestLock_; std::set<std::shared_ptr<dht::http::Request>> requests_; std::unique_ptr<ServerAccountCredentials> creds_; void sendRequest(const std::shared_ptr<dht::http::Request>& request); void clearRequest(const std::weak_ptr<dht::http::Request>& request); enum class TokenScope : unsigned { None = 0, Device, User, Admin }; std::mutex tokenLock_; std::string token_ {}; TokenScope tokenScope_ {}; std::chrono::steady_clock::time_point tokenExpire_ { std::chrono::steady_clock::time_point::min()}; unsigned authErrorCount {0}; using RequestQueue = std::queue<std::shared_ptr<dht::http::Request>>; RequestQueue pendingDeviceRequests_; RequestQueue pendingAccountRequests_; RequestQueue& getRequestQueue(TokenScope scope) { return scope == TokenScope::Device ? pendingDeviceRequests_ : pendingAccountRequests_; } bool hasAuthorization(TokenScope scope) const { return not token_.empty() and tokenScope_ >= scope and tokenExpire_ >= std::chrono::steady_clock::now(); } void setAuthHeaderFields(dht::http::Request& request) const; void sendDeviceRequest(const std::shared_ptr<dht::http::Request>& req); void sendAccountRequest(const std::shared_ptr<dht::http::Request>& req, const std::string& password); void authenticateDevice(); void authenticateAccount(const std::string& username, const std::string& password); void authFailed(TokenScope scope, int code); void authError(TokenScope scope); void onAuthEnded(const Json::Value& json, const dht::http::Response& response, TokenScope scope); std::function<void()> onNeedsMigration_; void setToken(std::string token, TokenScope scope, std::chrono::steady_clock::time_point expiration); }; } // namespace jami
4,821
C++
.h
109
36.486239
105
0.675197
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
752,018
channel_handler.h
savoirfairelinux_jami-daemon/src/jamidht/channel_handler.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 <dhtnet/multiplexed_socket.h> namespace jami { using DeviceId = dht::PkId; using ConnectCb = std::function<void(std::shared_ptr<dhtnet::ChannelSocket>, const DeviceId&)>; /** * A Channel handler is used to make the link between JamiAccount and ConnectionManager * Its role is to manage channels for a protocol (git/sip/etc) */ class ChannelHandlerInterface { public: virtual ~ChannelHandlerInterface() {}; /** * Ask for a new channel * @param deviceId The device to connect * @param name The name of the channel * @param cb The callback to call when connected (can be immediate if already connected) */ virtual void connect(const DeviceId& deviceId, const std::string& name, ConnectCb&& cb) = 0; /** * Determine if we accept or not the request. Called when ConnectionManager receives a request * @param peer Peer who asked * @param name The name of the channel * @return if we accept or not */ virtual bool onRequest(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name) = 0; /** * Called when ConnectionManager has a new channel ready * @param peer Connected peer * @param name The name of the channel * @param channel Channel to handle */ virtual void onReady(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) = 0; }; } // namespace jami
2,329
C++
.h
56
37.125
111
0.682259
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
752,019
account_manager.h
savoirfairelinux_jami-daemon/src/jamidht/account_manager.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 #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "contact_list.h" #include "logger.h" #if HAVE_RINGNS #include "namedirectory.h" #endif #include <opendht/crypto.h> #include <optional> #include <functional> #include <map> #include <string> #include <filesystem> namespace dht { class DhtRunner; } namespace jami { using DeviceId = dht::PkId; struct AccountArchive; struct AccountInfo { dht::crypto::Identity identity; std::unique_ptr<ContactList> contacts; std::string accountId; std::string deviceId; std::shared_ptr<dht::crypto::PublicKey> devicePk; std::shared_ptr<dht::Value> announce; std::string ethAccount; std::string username; std::string photo; }; template<typename To, typename From> std::unique_ptr<To> dynamic_unique_cast(std::unique_ptr<From>&& p) { if (auto cast = dynamic_cast<To*>(p.get())) { std::unique_ptr<To> result(cast); p.release(); return result; } return {}; } class AccountManager: public std::enable_shared_from_this<AccountManager> { public: using OnChangeCallback = ContactList::OnChangeCallback; using clock = std::chrono::system_clock; using time_point = clock::time_point; using OnNewDeviceCb = std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>; using OnDeviceAnnouncedCb = std::function<void()>; AccountManager(const std::filesystem::path& path, const std::string& nameServer) : path_(path) , nameDir_(NameDirectory::instance(nameServer)) {}; virtual ~AccountManager(); constexpr static const char* const DHT_TYPE_NS = "cx.ring"; // Auth enum class AuthError { UNKNOWN, INVALID_ARGUMENTS, SERVER_ERROR, NETWORK }; using AuthSuccessCallback = std::function<void(const AccountInfo& info, const std::map<std::string, std::string>& config, std::string&& receipt, std::vector<uint8_t>&& receipt_signature)>; using AuthFailureCallback = std::function<void(AuthError error, const std::string& message)>; using DeviceSyncCallback = std::function<void(DeviceSync&& syncData)>; using CertRequest = std::future<std::unique_ptr<dht::crypto::CertificateRequest>>; using PrivateKey = std::shared_future<std::shared_ptr<dht::crypto::PrivateKey>>; CertRequest buildRequest(PrivateKey fDeviceKey); struct AccountCredentials { std::string scheme; std::string uri; std::string password_scheme; std::string password; virtual ~AccountCredentials() {}; }; virtual void initAuthentication(const std::string& accountId, PrivateKey request, std::string deviceName, std::unique_ptr<AccountCredentials> credentials, AuthSuccessCallback onSuccess, AuthFailureCallback onFailure, const OnChangeCallback& onChange) = 0; virtual bool changePassword(const std::string& password_old, const std::string& password_new) = 0; virtual void syncDevices() = 0; virtual void onSyncData(DeviceSync&& device, bool checkDevice = true); virtual bool isPasswordValid(const std::string& /*password*/) { return false; }; virtual std::vector<uint8_t> getPasswordKey(const std::string& /*password*/) { return {}; }; dht::crypto::Identity loadIdentity(const std::string& accountId, const std::string& crt_path, const std::string& key_path, const std::string& key_pwd) const; const AccountInfo* useIdentity(const std::string& accountId, const dht::crypto::Identity& id, const std::string& receipt, const std::vector<uint8_t>& receiptSignature, const std::string& username, const OnChangeCallback& onChange); Json::Value announceFromReceipt(const std::string& receipt); void setDht(const std::shared_ptr<dht::DhtRunner>& dht) { dht_ = dht; } virtual void startSync(const OnNewDeviceCb& cb, const OnDeviceAnnouncedCb& dcb, bool publishPresence = true); const AccountInfo* getInfo() const { return info_.get(); } void reloadContacts(); // Device management enum class AddDeviceResult { SUCCESS_SHOW_PIN = 0, ERROR_CREDENTIALS, ERROR_NETWORK, }; using AddDeviceCallback = std::function<void(AddDeviceResult, std::string pin)>; enum class RevokeDeviceResult { SUCCESS = 0, ERROR_CREDENTIALS, ERROR_NETWORK, }; using RevokeDeviceCallback = std::function<void(RevokeDeviceResult)>; virtual void addDevice(const std::string& /*password*/, AddDeviceCallback) {}; virtual bool revokeDevice(const std::string& /*device*/, std::string_view /*scheme*/, const std::string& /*password*/, RevokeDeviceCallback) { return false; }; const std::map<dht::PkId, KnownDevice>& getKnownDevices() const; bool foundAccountDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, const std::string& name = {}, const time_point& last_sync = time_point::min()); // bool removeAccountDevice(const dht::InfoHash& device); void setAccountDeviceName(/*const dht::InfoHash& device, */ const std::string& name); std::string getAccountDeviceName() const; void forEachDevice(const dht::InfoHash& to, std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op, std::function<void(bool)>&& end = {}); using PeerCertificateCb = std::function<void(const std::shared_ptr<dht::crypto::Certificate>& crt, const dht::InfoHash& peer_account)>; void onPeerMessage(const dht::crypto::PublicKey& peer_device, bool allowPublic, PeerCertificateCb&& cb); bool onPeerCertificate(const std::shared_ptr<dht::crypto::Certificate>& crt, bool allowPublic, dht::InfoHash& account_id); /** * Inform that a potential peer device have been found. * Returns true only if the device certificate is a valid device certificate. * In that case (true is returned) the account_id parameter is set to the peer account ID. */ static bool foundPeerDevice(const std::shared_ptr<dht::crypto::Certificate>& crt, dht::InfoHash& account_id); // Contact requests std::vector<std::map<std::string, std::string>> getTrustRequests() const; // Note: includeConversation used for compatibility test, do not use if not in test env. bool acceptTrustRequest(const std::string& from, bool includeConversation = true); bool discardTrustRequest(const std::string& from); void sendTrustRequest(const std::string& to, const std::string& convId, const std::vector<uint8_t>& payload); void sendTrustRequestConfirm(const dht::InfoHash& to, const std::string& conversationId); // TODO ideally no convId here // Contact /** * Add contact to the account contact list. * Set confirmed if we know the contact also added us. */ bool addContact(const dht::InfoHash& uri, bool confirmed = false, const std::string& conversationId = ""); void removeContact(const std::string& uri, bool banned = true); void removeContactConversation(const std::string& uri); // for non swarm contacts void updateContactConversation(const std::string& uri, const std::string& convId); std::vector<std::map<std::string, std::string>> getContacts(bool includeRemoved = false) const; /** Obtain details about one account contact in serializable form. */ std::map<std::string, std::string> getContactDetails(const std::string& uri) const; virtual bool findCertificate( const dht::InfoHash& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {}); virtual bool findCertificate( const dht::PkId& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {}); bool setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status); bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert, dhtnet::tls::TrustStore::PermissionStatus status, bool local = true); std::vector<std::string> getCertificatesByStatus(dhtnet::tls::TrustStore::PermissionStatus status); dhtnet::tls::TrustStore::PermissionStatus getCertificateStatus(const std::string& cert_id) const; bool isAllowed(const crypto::Certificate& crt, bool allowPublic = false); static std::shared_ptr<dht::Value> parseAnnounce(const std::string& announceBase64, const std::string& accountId, const std::string& deviceSha1); // Name resolver using LookupCallback = NameDirectory::LookupCallback; using SearchResult = NameDirectory::SearchResult; using SearchCallback = NameDirectory::SearchCallback; using RegistrationCallback = NameDirectory::RegistrationCallback; using SearchResponse = NameDirectory::Response; virtual void lookupUri(const std::string& name, const std::string& defaultServer, LookupCallback cb); virtual void lookupAddress(const std::string& address, LookupCallback cb); virtual bool searchUser(const std::string& /*query*/, SearchCallback /*cb*/) { return false; } virtual void registerName(const std::string& name, std::string_view scheme, const std::string& password, RegistrationCallback cb) = 0; dhtnet::tls::CertificateStore& certStore() const; protected: std::filesystem::path path_; OnChangeCallback onChange_; std::unique_ptr<AccountInfo> info_; std::string accountId_; std::shared_ptr<dht::DhtRunner> dht_; std::reference_wrapper<NameDirectory> nameDir_; }; } // namespace jami
11,559
C++
.h
232
39.418103
113
0.6348
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
752,020
conversation.h
savoirfairelinux_jami-daemon/src/jamidht/conversation.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 "jamidht/conversationrepository.h" #include "conversationrepository.h" #include "swarm/swarm_protocol.h" #include "jami/conversation_interface.h" #include "jamidht/typers.h" #include <json/json.h> #include <msgpack.hpp> #include <functional> #include <string> #include <vector> #include <map> #include <memory> #include <set> #include <asio.hpp> namespace dhtnet { class ChannelSocket; } // namespace dhtnet namespace jami { namespace ConversationMapKeys { static constexpr const char* ID = "id"; static constexpr const char* CREATED = "created"; static constexpr const char* REMOVED = "removed"; static constexpr const char* ERASED = "erased"; static constexpr const char* MEMBERS = "members"; static constexpr const char* LAST_DISPLAYED = "lastDisplayed"; static constexpr const char* PREFERENCES = "preferences"; static constexpr const char* ACTIVE_CALLS = "activeCalls"; static constexpr const char* HOSTED_CALLS = "hostedCalls"; static constexpr const char* CACHED = "cached"; static constexpr const char* RECEIVED = "received"; static constexpr const char* DECLINED = "declined"; static constexpr const char* FROM = "from"; static constexpr const char* CONVERSATIONID = "conversationId"; static constexpr const char* METADATAS = "metadatas"; } // namespace ConversationMapKeys namespace ConversationPreferences { static constexpr const char* HOST_CONFERENCES = "hostConferences"; } /** * A ConversationRequest is a request which corresponds to a trust request, but for conversations * It's signed by the sender and contains the members list, the conversationId, and the metadatas * such as the conversation's vcard, etc. (TODO determine) * Transmitted via the UDP DHT */ struct ConversationRequest { std::string conversationId; std::string from; std::map<std::string, std::string> metadatas; time_t received {0}; time_t declined {0}; ConversationRequest() = default; ConversationRequest(const Json::Value& json); Json::Value toJson() const; std::map<std::string, std::string> toMap() const; bool operator==(const ConversationRequest& o) const { auto m = toMap(); auto om = o.toMap(); return m.size() == om.size() && std::equal(m.begin(), m.end(), om.begin()); } bool isOneToOne() const { try { return metadatas.at("mode") == "0"; } catch (...) {} return true; } MSGPACK_DEFINE_MAP(from, conversationId, metadatas, received, declined) }; struct ConvInfo { std::string id {}; time_t created {0}; time_t removed {0}; time_t erased {0}; std::set<std::string> members; std::string lastDisplayed {}; ConvInfo() = default; ConvInfo(const ConvInfo&) = default; ConvInfo(ConvInfo&&) = default; ConvInfo(const std::string& id) : id(id) {}; explicit ConvInfo(const Json::Value& json); bool isRemoved() const { return removed >= created; } ConvInfo& operator=(const ConvInfo&) = default; ConvInfo& operator=(ConvInfo&&) = default; Json::Value toJson() const; MSGPACK_DEFINE_MAP(id, created, removed, erased, members, lastDisplayed) }; class JamiAccount; class ConversationRepository; class TransferManager; enum class ConversationMode; using OnPullCb = std::function<void(bool fetchOk)>; using OnLoadMessages = std::function<void(std::vector<std::map<std::string, std::string>>&& messages)>; using OnLoadMessages2 = std::function<void(std::vector<libjami::SwarmMessage>&& messages)>; using OnCommitCb = std::function<void(const std::string&)>; using OnDoneCb = std::function<void(bool, const std::string&)>; using OnMultiDoneCb = std::function<void(const std::vector<std::string>&)>; using OnMembersChanged = std::function<void(const std::set<std::string>&)>; using DeviceId = dht::PkId; using GitSocketList = std::map<DeviceId, std::shared_ptr<dhtnet::ChannelSocket>>; using ChannelCb = std::function<bool(const std::shared_ptr<dhtnet::ChannelSocket>&)>; using NeedSocketCb = std::function<void(const std::string&, const std::string&, ChannelCb&&, const std::string&)>; class Conversation : public std::enable_shared_from_this<Conversation> { public: Conversation(const std::shared_ptr<JamiAccount>& account, ConversationMode mode, const std::string& otherMember = ""); Conversation(const std::shared_ptr<JamiAccount>& account, const std::string& conversationId = ""); Conversation(const std::shared_ptr<JamiAccount>& account, const std::string& remoteDevice, const std::string& conversationId); ~Conversation(); /** * Print the state of the DRT linked to the conversation */ void monitor(); #ifdef LIBJAMI_TESTABLE enum class BootstrapStatus { FAILED, FALLBACK, SUCCESS }; /** * Used by the tests to get whenever the DRT is connected/disconnected */ void onBootstrapStatus(const std::function<void(std::string, BootstrapStatus)>& cb); #endif /** * Bootstrap swarm manager to other peers * @param onBootstraped Callback called when connection is successfully established * @param knownDevices List of account's known devices */ void bootstrap(std::function<void()> onBootstraped, const std::vector<DeviceId>& knownDevices); /** * Refresh active calls. * @note: If the host crash during a call, when initializing, we need to update * and commit all the crashed calls * @return Commits added */ std::vector<std::string> commitsEndedCalls(); void onMembersChanged(OnMembersChanged&& cb); /** * Set the callback that will be called whenever a new socket will be needed * @param cb */ void onNeedSocket(NeedSocketCb cb); /** * Add swarm connection to the DRT * @param channel Related channel */ void addSwarmChannel(std::shared_ptr<dhtnet::ChannelSocket> channel); /** * Get conversation's id * @return conversation Id */ std::string id() const; // Member management /** * Add conversation member * @param uri Member to add * @param cb On done cb */ void addMember(const std::string& contactUri, const OnDoneCb& cb = {}); void removeMember(const std::string& contactUri, bool isDevice, const OnDoneCb& cb = {}); /** * @param includeInvited If we want invited members * @param includeLeft If we want left members * @param includeBanned If we want banned members * @return a vector of member details: * { * "uri":"xxx", * "role":"member/admin/invited", * "lastDisplayed":"id" * ... * } */ std::vector<std::map<std::string, std::string>> getMembers(bool includeInvited = false, bool includeLeft = false, bool includeBanned = false) const; /** * @param filter If we want to remove one member * @param filteredRoles If we want to ignore some roles * @return members' uris */ std::set<std::string> memberUris( std::string_view filter = {}, const std::set<MemberRole>& filteredRoles = {MemberRole::INVITED, MemberRole::LEFT, MemberRole::BANNED}) const; /** * Get peers to sync with. This is mostly managed by the DRT * @return some mobile nodes and all connected nodes */ std::vector<NodeId> peersToSyncWith() const; /** * Check if we're at least connected to one node * @return if the DRT is connected */ bool isBootstraped() const; /** * Retrieve the uri from a deviceId * @note used by swarm manager (peersToSyncWith) * @param deviceId * @return corresponding issuer */ std::string uriFromDevice(const std::string& deviceId) const; /** * Join a conversation * @return commit id to send */ std::string join(); /** * Test if an URI is a member * @param uri URI to test * @return true if uri is a member */ bool isMember(const std::string& uri, bool includeInvited = false) const; bool isBanned(const std::string& uri) const; // Message send void sendMessage(std::string&& message, const std::string& type = "text/plain", const std::string& replyTo = "", OnCommitCb&& onCommit = {}, OnDoneCb&& cb = {}); void sendMessage(Json::Value&& message, const std::string& replyTo = "", OnCommitCb&& onCommit = {}, OnDoneCb&& cb = {}); // Note: used for replay. Should not be used by clients void sendMessages(std::vector<Json::Value>&& messages, OnMultiDoneCb&& cb = {}); /** * Get a range of messages * @param cb The callback when loaded * @param options The log options */ void loadMessages(OnLoadMessages cb, const LogOptions& options); /** * Get a range of messages * @param cb The callback when loaded * @param options The log options */ void loadMessages2(const OnLoadMessages2& cb, const LogOptions& options); /** * Clear all cached messages */ void clearCache(); /** * Retrieve one commit * @param commitId * @return The commit if found */ std::optional<std::map<std::string, std::string>> getCommit(const std::string& commitId) const; /** * Get last commit id * @return last commit id */ std::string lastCommitId() const; /** * Fetch and merge from peer * @param deviceId Peer device * @param cb On pulled callback * @param commitId Commit id that triggered this fetch * @return true if callback will be called later */ bool pull(const std::string& deviceId, OnPullCb&& cb, std::string commitId = ""); /** * Fetch new commits and re-ask for waiting files * @param member * @param deviceId * @param cb cf pull() * @param commitId cf pull() */ void sync(const std::string& member, const std::string& deviceId, OnPullCb&& cb, std::string commitId = ""); /** * Generate an invitation to send to new contacts * @return the invite to send */ std::map<std::string, std::string> generateInvitation() const; /** * Leave a conversation * @return commit id to send */ std::string leave(); /** * Set a conversation as removing (when loading convInfo and still not sync) * @todo: not a big fan to see this here. can be set in the constructor * cause it's used by jamiaccount when loading conversations */ void setRemovingFlag(); /** * Check if we are removing the conversation * @return true if left the room */ bool isRemoving(); /** * Erase all related datas */ void erase(); /** * Get conversation's mode * @return the mode */ ConversationMode mode() const; /** * One to one util, get initial members * @return initial members */ std::vector<std::string> getInitialMembers() const; bool isInitialMember(const std::string& uri) const; /** * Change repository's infos * @param map New infos (supported keys: title, description, avatar) * @param cb On commited */ void updateInfos(const std::map<std::string, std::string>& map, const OnDoneCb& cb = {}); /** * Change user's preferences * @param map New preferences */ void updatePreferences(const std::map<std::string, std::string>& map); /** * Retrieve current infos (title, description, avatar, mode) * @return infos */ std::map<std::string, std::string> infos() const; /** * Retrieve current preferences (color, notification, etc) * @param includeLastModified If we want to know when the preferences were modified * @return preferences */ std::map<std::string, std::string> preferences(bool includeLastModified) const; std::vector<uint8_t> vCard() const; /////// File transfer /** * Access to transfer manager */ std::shared_ptr<TransferManager> dataTransfer() const; /** * Choose if we can accept channel request * @param member member to check * @param fileId file transfer to check (needs to be waiting) * @param verifyShaSum for debug only * @return if we accept the channel request */ bool onFileChannelRequest(const std::string& member, const std::string& fileId, bool verifyShaSum = true) const; /** * Adds a file to the waiting list and ask members * @param interactionId Related interaction id * @param fileId Related id * @param path Destination * @param member Member if we know from who to pull file * @param deviceId Device if we know from who to pull file * @param start Offset (unused for now) * @param end Offset (unused) * @return id of the file */ bool downloadFile(const std::string& interactionId, const std::string& fileId, const std::string& path, const std::string& member = "", const std::string& deviceId = "", std::size_t start = 0, std::size_t end = 0); /** * Reset fetched information */ void clearFetched(); /** * Store information about who fetch or not. This simplify sync (sync when a device without the * last fetch is detected) * @param deviceId * @param commitId */ void hasFetched(const std::string& deviceId, const std::string& commitId); /** * Store last read commit (returned in getMembers) * @param uri Of the member * @param interactionId Last interaction displayed * @return if updated */ bool setMessageDisplayed(const std::string& uri, const std::string& interactionId); /** * Retrieve last displayed and fetch status per member * @return A map with the following structure: * {uri, { * {"fetch", "commitId"}, * {"fetched_ts", "timestamp"}, * {"read", "commitId"}, * {"read_ts", "timestamp"} * } * } */ std::map<std::string, std::map<std::string, std::string>> messageStatus() const; /** * Update fetch/read status * @param messageStatus A map with the following structure: * {uri, { * {"fetch", "commitId"}, * {"fetched_ts", "timestamp"}, * {"read", "commitId"}, * {"read_ts", "timestamp"} * } * } */ void updateMessageStatus(const std::map<std::string, std::map<std::string, std::string>>& messageStatus); void onMessageStatusChanged(const std::function<void(const std::map<std::string, std::map<std::string, std::string>>&)>& cb); /** * Retrieve how many interactions there is from HEAD to interactionId * @param toId "" for getting the whole history * @param fromId "" => HEAD * @param authorURI author to stop counting * @return number of interactions since interactionId */ uint32_t countInteractions(const std::string& toId, const std::string& fromId = "", const std::string& authorUri = "") const; /** * Search in the conversation via a filter * @param req Id of the request * @param filter Parameters for the search * @param flag To check when search is finished * @note triggers messagesFound */ void search(uint32_t req, const Filter& filter, const std::shared_ptr<std::atomic_int>& flag) const; /** * Host a conference in the conversation * @note the message must have "confId" * @note Update hostedCalls_ and commit in the conversation * @param message message to commit * @param cb callback triggered when committed */ void hostConference(Json::Value&& message, OnDoneCb&& cb = {}); /** * Announce the end of a call * @note the message must have "confId" * @note called when conference is finished * @param message message to commit * @param cb callback triggered when committed */ void removeActiveConference(Json::Value&& message, OnDoneCb&& cb = {}); /** * Check if we're currently hosting this conference * @param confId * @return true if hosting */ bool isHosting(const std::string& confId) const; /** * Return current detected calls * @return a vector of map with the following keys: "id", "uri", "device" */ std::vector<std::map<std::string, std::string>> currentCalls() const; /** * Git operations will need a ChannelSocket for cloning/fetching commits * Because libgit2 is a C library, we store the pointer in the corresponding conversation * and the GitTransport will inject to libgit2 whenever needed */ std::shared_ptr<dhtnet::ChannelSocket> gitSocket(const DeviceId& deviceId) const; void addGitSocket(const DeviceId& deviceId, const std::shared_ptr<dhtnet::ChannelSocket>& socket); void removeGitSocket(const DeviceId& deviceId); /** * Stop SwarmManager, bootstrap and gitSockets */ void shutdownConnections(); /** * Used to avoid multiple connections, we just check if we got a swarm channel with a specific * device * @param deviceId */ bool hasSwarmChannel(const std::string& deviceId); /** * If we change from one network to one another, we will need to update the state of the connections */ void connectivityChanged(); /** * @return getAllNodes() Nodes that are linked to the conversation */ std::vector<jami::DeviceId> getDeviceIdList() const; /** * Get Typers object * @return Typers object */ std::shared_ptr<Typers> typers() const; private: std::shared_ptr<Conversation> shared() { return std::static_pointer_cast<Conversation>(shared_from_this()); } std::shared_ptr<Conversation const> shared() const { return std::static_pointer_cast<Conversation const>(shared_from_this()); } std::weak_ptr<Conversation> weak() { return std::static_pointer_cast<Conversation>(shared_from_this()); } std::weak_ptr<Conversation const> weak() const { return std::static_pointer_cast<Conversation const>(shared_from_this()); } // Private because of weak() /** * Used by bootstrap() to launch the fallback * @param ec * @param members Members to try to connect */ void checkBootstrapMember(const asio::error_code& ec, std::vector<std::map<std::string, std::string>> members); class Impl; std::unique_ptr<Impl> pimpl_; }; } // namespace jami
20,287
C++
.h
537
31.482309
129
0.634346
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
752,021
conversation_channel_handler.h
savoirfairelinux_jami-daemon/src/jamidht/conversation_channel_handler.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 "jamidht/channel_handler.h" #include "jamidht/jamiaccount.h" #include <dhtnet/connectionmanager.h> namespace jami { /** * Manages Conversation's channels */ class ConversationChannelHandler : public ChannelHandlerInterface { public: ConversationChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm); ~ConversationChannelHandler(); /** * Ask for a new git channel * @param deviceId The device to connect * @param name The name of the channel * @param cb The callback to call when connected (can be immediate if already connected) */ void connect(const DeviceId& deviceId, const std::string& name, ConnectCb&& cb) override; /** * Determine if we accept or not the git request * @param deviceId device who asked * @param name name asked * @return if the channel is for a valid conversation and device not banned */ bool onRequest(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name) override; /** * TODO, this needs to extract gitservers from JamiAccount */ void onReady(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) override; private: std::weak_ptr<JamiAccount> account_; dhtnet::ConnectionManager& connectionManager_; }; } // namespace jami
2,203
C++
.h
54
36.87037
108
0.711485
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
752,022
jamiaccount.h
savoirfairelinux_jami-daemon/src/jamidht/jamiaccount.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 "def.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sip/sipaccountbase.h" #include "jami/datatransfer_interface.h" #include "jamidht/conversation.h" #include "data_transfer.h" #include "uri.h" #include "jamiaccount_config.h" #include "noncopyable.h" #include "ring_types.h" // enable_if_base_of #include "scheduled_executor.h" #include "gitserver.h" #include "channel_handler.h" #include "conversation_module.h" #include "sync_module.h" #include "conversationrepository.h" #include <dhtnet/diffie-hellman.h> #include <dhtnet/tls_session.h> #include <dhtnet/multiplexed_socket.h> #include <dhtnet/certstore.h> #include <dhtnet/connectionmanager.h> #include <dhtnet/upnp/mapping.h> #include <dhtnet/ip_utils.h> #include <dhtnet/fileutils.h> #include <opendht/dhtrunner.h> #include <opendht/default_types.h> #include <pjsip/sip_types.h> #include <json/json.h> #include <chrono> #include <functional> #include <future> #include <list> #include <map> #include <optional> #include <vector> #include <filesystem> #if HAVE_RINGNS #include "namedirectory.h" #endif namespace dev { template<unsigned N> class FixedHash; using h160 = FixedHash<20>; using Address = h160; } // namespace dev namespace jami { class IceTransport; struct Contact; struct AccountArchive; class DhtPeerConnector; class AccountManager; struct AccountInfo; class SipTransport; class ChanneledOutgoingTransfer; class SyncModule; struct TextMessageCtx; using SipConnectionKey = std::pair<std::string /* uri */, DeviceId>; static constexpr const char MIME_TYPE_IM_COMPOSING[] {"application/im-iscomposing+xml"}; /** * @brief Ring Account is build on top of SIPAccountBase and uses DHT to handle call connectivity. */ class JamiAccount : public SIPAccountBase { public: constexpr static auto ACCOUNT_TYPE = ACCOUNT_TYPE_JAMI; constexpr static const std::pair<uint16_t, uint16_t> DHT_PORT_RANGE {4000, 8888}; constexpr static int ICE_STREAMS_COUNT {1}; constexpr static int ICE_COMP_COUNT_PER_STREAM {1}; std::string_view getAccountType() const override { return ACCOUNT_TYPE; } std::shared_ptr<JamiAccount> shared() { return std::static_pointer_cast<JamiAccount>(shared_from_this()); } std::shared_ptr<JamiAccount const> shared() const { return std::static_pointer_cast<JamiAccount const>(shared_from_this()); } std::weak_ptr<JamiAccount> weak() { return std::static_pointer_cast<JamiAccount>(shared_from_this()); } std::weak_ptr<JamiAccount const> weak() const { return std::static_pointer_cast<JamiAccount const>(shared_from_this()); } const std::filesystem::path& getPath() const { return idPath_; } const JamiAccountConfig& config() const { return *static_cast<const JamiAccountConfig*>(&Account::config()); } JamiAccountConfig::Credentials consumeConfigCredentials() { auto conf = static_cast<JamiAccountConfig*>(config_.get()); return std::move(conf->credentials); } void loadConfig() override; /** * Constructor * @param accountID The account identifier */ JamiAccount(const std::string& accountId); ~JamiAccount() noexcept; /** * Retrieve volatile details such as recent registration errors * @return std::map< std::string, std::string > The account volatile details */ virtual std::map<std::string, std::string> getVolatileAccountDetails() const override; std::unique_ptr<AccountConfig> buildConfig() const override { return std::make_unique<JamiAccountConfig>(getAccountID(), idPath_); } /** * Adds an account id to the list of accounts to track on the DHT for * buddy presence. * * @param buddy_id The buddy id. */ void trackBuddyPresence(const std::string& buddy_id, bool track); /** * Tells for each tracked account id if it has been seen online so far * in the last DeviceAnnouncement::TYPE.expiration minutes. * * @return map of buddy_uri to bool (online or not) */ std::map<std::string, bool> getTrackedBuddyPresence() const; void setActiveCodecs(const std::vector<unsigned>& list) override; /** * Connect to the DHT. */ void doRegister() override; /** * Disconnect from the DHT. */ void doUnregister(std::function<void(bool)> cb = {}) override; /** * Set the registration state of the specified link * @param state The registration state of underlying VoIPLink */ void setRegistrationState(RegistrationState state, int detail_code = 0, const std::string& detail_str = {}) override; /** * @return pj_str_t "From" uri based on account information. * From RFC3261: "The To header field first and foremost specifies the desired * logical" recipient of the request, or the address-of-record of the * user or resource that is the target of this request. [...] As such, it is * very important that the From URI not contain IP addresses or the FQDN * of the host on which the UA is running, since these are not logical * names." */ std::string getFromUri() const override; /** * This method adds the correct scheme, hostname and append * the ;transport= parameter at the end of the uri, in accordance with RFC3261. * It is expected that "port" is present in the internal hostname_. * * @return pj_str_t "To" uri based on @param username * @param username A string formatted as : "username" */ std::string getToUri(const std::string& username) const override; /** * In the current version, "srv" uri is obtained in the preformated * way: hostname:port. This method adds the correct scheme and append * the ;transport= parameter at the end of the uri, in accordance with RFC3261. * * @return pj_str_t "server" uri based on @param hostPort * @param hostPort A string formatted as : "hostname:port" */ std::string getServerUri() const { return ""; }; void setIsComposing(const std::string& conversationUri, bool isWriting) override; bool setMessageDisplayed(const std::string& conversationUri, const std::string& messageId, int status) override; /** * Get the contact header for * @return The contact header based on account information */ std::string getContactHeader(const std::shared_ptr<SipTransport>& sipTransport); /* Returns true if the username and/or hostname match this account */ MatchRank matches(std::string_view username, std::string_view hostname) const override; /** * Create outgoing SIPCall. * @note Accepts several urls: * + jami:uri for calling someone * + swarm:id for calling a group (will host or join if an active call is detected) * + rdv:id/uri/device/confId to join a specific conference hosted on (uri, device) * @param[in] toUrl The address to call * @param[in] mediaList list of medias * @return A shared pointer on the created call. */ std::shared_ptr<Call> newOutgoingCall(std::string_view toUrl, const std::vector<libjami::MediaMap>& mediaList) override; /** * Create incoming SIPCall. * @param[in] from The origin of the call * @param mediaList A list of media * @param sipTr: SIP Transport * @return A shared pointer on the created call. */ std::shared_ptr<SIPCall> newIncomingCall( const std::string& from, const std::vector<libjami::MediaMap>& mediaList, const std::shared_ptr<SipTransport>& sipTr = {}) override; void onTextMessage(const std::string& id, const std::string& from, const std::string& deviceId, const std::map<std::string, std::string>& payloads) override; void loadConversation(const std::string& convId); virtual bool isTlsEnabled() const override { return true; } bool isSrtpEnabled() const override { return true; } virtual bool getSrtpFallback() const override { return false; } bool setCertificateStatus(const std::string& cert_id, dhtnet::tls::TrustStore::PermissionStatus status); bool setCertificateStatus(const std::shared_ptr<crypto::Certificate>& cert, dhtnet::tls::TrustStore::PermissionStatus status, bool local = true); std::vector<std::string> getCertificatesByStatus( dhtnet::tls::TrustStore::PermissionStatus status); bool findCertificate(const std::string& id); bool findCertificate( const dht::InfoHash& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {}); bool findCertificate( const dht::PkId& h, std::function<void(const std::shared_ptr<dht::crypto::Certificate>&)>&& cb = {}); /* contact requests */ std::vector<std::map<std::string, std::string>> getTrustRequests() const; // Note: includeConversation used for compatibility test. Do not change bool acceptTrustRequest(const std::string& from, bool includeConversation = true); bool discardTrustRequest(const std::string& from); void declineConversationRequest(const std::string& conversationId); /** * Add contact to the account contact list. * Set confirmed if we know the contact also added us. */ void addContact(const std::string& uri, bool confirmed = false); void removeContact(const std::string& uri, bool banned = true); std::vector<std::map<std::string, std::string>> getContacts(bool includeRemoved = false) const; /// /// Obtain details about one account contact in serializable form. /// std::map<std::string, std::string> getContactDetails(const std::string& uri) const; void sendTrustRequest(const std::string& to, const std::vector<uint8_t>& payload); void sendMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t id, bool retryOnTimeout = true, bool onlyConnected = false) override; uint64_t sendTextMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t refreshToken = 0, bool onlyConnected = false) override; void sendInstantMessage(const std::string& convId, const std::map<std::string, std::string>& msg); /** * Create and return ICE options. */ dhtnet::IceTransportOptions getIceOptions() const noexcept override; void getIceOptions(std::function<void(dhtnet::IceTransportOptions&&)> cb) const noexcept; dhtnet::IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const override; /* Devices */ void addDevice(const std::string& password); /** * Export the archive to a file * @param destinationPath * @param (optional) password, if not provided, will update the contacts only if the archive * doesn't have a password * @return if the archive was exported */ bool exportArchive(const std::string& destinationPath, std::string_view scheme = {}, const std::string& password = {}); bool revokeDevice(const std::string& device, std::string_view scheme = {}, const std::string& password = {}); std::map<std::string, std::string> getKnownDevices() const; bool isPasswordValid(const std::string& password); std::vector<uint8_t> getPasswordKey(const std::string& password); bool changeArchivePassword(const std::string& password_old, const std::string& password_new); void connectivityChanged() override; // overloaded methods void flush() override; #if HAVE_RINGNS void lookupName(const std::string& name); void lookupAddress(const std::string& address); void registerName(const std::string& name, const std::string& scheme, const std::string& password); #endif bool searchUser(const std::string& nameQuery); /// \return true if the given DHT message identifier has been treated /// \note if message has not been treated yet this method store this id and returns true at /// further calls bool isMessageTreated(dht::Value::Id id); std::shared_ptr<dht::DhtRunner> dht() { return dht_; } const dht::crypto::Identity& identity() const { return id_; } void forEachDevice(const dht::InfoHash& to, std::function<void(const std::shared_ptr<dht::crypto::PublicKey>&)>&& op, std::function<void(bool)>&& end = {}); bool setPushNotificationToken(const std::string& pushDeviceToken = "") override; bool setPushNotificationTopic(const std::string& topic) override; bool setPushNotificationConfig(const std::map<std::string, std::string>& data) override; /** * To be called by clients with relevant data when a push notification is received. */ void pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data); std::string getUserUri() const override; /** * Get last messages (should be used to retrieve messages when launching the client) * @param base_timestamp */ std::vector<libjami::Message> getLastMessages(const uint64_t& base_timestamp) override; /** * Start Publish the Jami Account onto the Network */ void startAccountPublish(); /** * Start Discovery the Jami Account from the Network */ void startAccountDiscovery(); void saveConfig() const override; inline void editConfig(std::function<void(JamiAccountConfig& conf)>&& edit) { Account::editConfig( [&](AccountConfig& conf) { edit(*static_cast<JamiAccountConfig*>(&conf)); }); } /** * Get current discovered peers account id and display name */ std::map<std::string, std::string> getNearbyPeers() const override; std::map<std::string, std::string> getProfileVcard() const; void sendProfileToPeers(); /** * Update the profile vcard and send it to peers * @param displayName Current or new display name * @param avatar Current or new avatar * @param flag 0 for path to avatar, 1 for base64 avatar */ void updateProfile(const std::string& displayName, const std::string& avatar, const uint64_t& flag); #ifdef LIBJAMI_TESTABLE dhtnet::ConnectionManager& connectionManager() { return *connectionManager_; } /** * Only used for tests, disable sha3sum verification for transfers. * @param newValue */ void noSha3sumVerification(bool newValue); void publishPresence(bool newValue) { publishPresence_ = newValue; } #endif /** * This should be called before flushing the account. * ConnectionManager needs the account to exists */ void shutdownConnections(); std::string_view currentDeviceId() const; // Received a new commit notification bool handleMessage(const std::string& from, const std::pair<std::string, std::string>& message) override; void monitor(); // conversationId optional std::vector<std::map<std::string, std::string>> getConnectionList( const std::string& conversationId = ""); std::vector<std::map<std::string, std::string>> getChannelList(const std::string& connectionId); // File transfer void sendFile(const std::string& conversationId, const std::filesystem::path& path, const std::string& name, const std::string& replyTo); void transferFile(const std::string& conversationId, const std::string& path, const std::string& deviceId, const std::string& fileId, const std::string& interactionId, size_t start = 0, size_t end = 0, const std::string& sha3Sum = "", uint64_t lastWriteTime = 0, std::function<void()> onFinished = {}); void askForFileChannel(const std::string& conversationId, const std::string& deviceId, const std::string& interactionId, const std::string& fileId, size_t start = 0, size_t end = 0); void askForProfile(const std::string& conversationId, const std::string& deviceId, const std::string& memberUri); /** * Retrieve linked transfer manager * @param id conversationId or empty for fallback * @return linked transfer manager */ std::shared_ptr<TransferManager> dataTransfer(const std::string& id = ""); /** * Used to get the instance of the ConversationModule class which is * responsible for managing conversations and messages between users. * @param noCreate whether or not to create a new instance * @return conversationModule instance */ ConversationModule* convModule(bool noCreation = false); SyncModule* syncModule(); /** * Check (via the cache) if we need to send our profile to a specific device * @param peerUri Uri that will receive the profile * @param deviceId Device that will receive the profile * @param sha3Sum SHA3 hash of the profile */ // Note: when swarm will be merged, this can be moved in transferManager bool needToSendProfile(const std::string& peerUri, const std::string& deviceId, const std::string& sha3Sum); /** * Send Profile via cached SIP connection * @param convId Conversation's identifier (can be empty for self profile on sync) * @param peerUri Uri that will receive the profile * @param deviceId Device that will receive the profile */ void sendProfile(const std::string& convId, const std::string& peerUri, const std::string& deviceId); /** * Send profile via cached SIP connection * @param peerUri Uri that will receive the profile * @param deviceId Device that will receive the profile */ void sendProfile(const std::string& peerUri, const std::string& deviceId); /** * Clear sent profiles (because of a removed contact or new trust request) * @param peerUri Uri used to clear cache */ void clearProfileCache(const std::string& peerUri); std::filesystem::path profilePath() const; const std::shared_ptr<AccountManager>& accountManager() { return accountManager_; } bool sha3SumVerify() const; /** * Change certificate's validity period * @param pwd Password for the archive * @param id Certificate to update ({} for updating the whole chain) * @param validity New validity * @note forceReloadAccount may be necessary to retrigger the migration */ bool setValidity(std::string_view scheme, const std::string& pwd, const dht::InfoHash& id, int64_t validity); /** * Try to reload the account to force the identity to be updated */ void forceReloadAccount(); void reloadContacts(); /** * Make sure appdata/contacts.yml contains correct information * @param removedConv The current removed conversations */ void unlinkConversations(const std::set<std::string>& removedConv); bool isValidAccountDevice(const dht::crypto::Certificate& cert) const; /** * Join incoming call to hosted conference * @param callId The call to join * @param destination conversation/uri/device/confId to join */ void handleIncomingConversationCall(const std::string& callId, const std::string& destination); /** * The DRT component is composed on some special nodes, that are usually present but not * connected. This kind of node corresponds to devices with push notifications & proxy and are * stored in the mobile nodes */ bool isMobile() const { return config().proxyEnabled and not config().deviceKey.empty(); } #ifdef LIBJAMI_TESTABLE std::map<Uri::Scheme, std::unique_ptr<ChannelHandlerInterface>>& channelHandlers() { return channelHandlers_; }; #endif dhtnet::tls::CertificateStore& certStore() const { return *certStore_; } /** * Check if a Device is connected * @param deviceId * @return true if connected */ bool isConnectedWith(const DeviceId& deviceId) const; /** * Send a presence note * @param note */ void sendPresenceNote(const std::string& note); private: NON_COPYABLE(JamiAccount); using clock = std::chrono::system_clock; using time_point = clock::time_point; /** * Private structures */ struct PendingCall; struct PendingMessage; struct BuddyInfo; struct DiscoveredPeer; inline std::string getProxyConfigKey() const { const auto& conf = config(); return dht::InfoHash::get(conf.proxyServer + conf.proxyListUrl).toString(); } /** * Compute archive encryption key and DHT storage location from password and PIN. */ static std::pair<std::vector<uint8_t>, dht::InfoHash> computeKeys(const std::string& password, const std::string& pin, bool previous = false); void trackPresence(const dht::InfoHash& h, BuddyInfo& buddy); void doRegister_(); const dht::ValueType USER_PROFILE_TYPE = {9, "User profile", std::chrono::hours(24 * 7)}; void startOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& toUri); void onConnectedOutgoingCall(const std::shared_ptr<SIPCall>& call, const std::string& to_id, dhtnet::IpAddr target); /** * Start a SIP Call * @param call The current call * @return true if all is correct */ bool SIPStartCall(SIPCall& call, const dhtnet::IpAddr& target); /** * Update tracking info when buddy appears offline. */ void onTrackedBuddyOffline(const dht::InfoHash&); /** * Update tracking info when buddy appears offline. */ void onTrackedBuddyOnline(const dht::InfoHash&); /** * Maps require port via UPnP and other async ops */ void registerAsyncOps(); /** * Add port mapping callback function. */ void onPortMappingAdded(uint16_t port_used, bool success); void forEachPendingCall(const DeviceId& deviceId, const std::function<void(const std::shared_ptr<SIPCall>&)>& cb); void loadAccountFromDHT(const std::string& archive_password, const std::string& archive_pin); void loadAccount(const std::string& archive_password_scheme = {}, const std::string& archive_password = {}, const std::string& archive_pin = {}, const std::string& archive_path = {}); std::vector<std::string> loadBootstrap() const; static std::pair<std::string, std::string> saveIdentity(const dht::crypto::Identity id, const std::filesystem::path& path, const std::string& name); void replyToIncomingIceMsg(const std::shared_ptr<SIPCall>&, const std::shared_ptr<IceTransport>&, const std::shared_ptr<IceTransport>&, const dht::IceCandidates&, const std::shared_ptr<dht::crypto::Certificate>& from_cert, const dht::InfoHash& from); void loadCachedUrl(const std::string& url, const std::filesystem::path& cachePath, const std::chrono::seconds& cacheDuration, std::function<void(const dht::http::Response& response)>); std::string getDhtProxyServer(const std::string& serverList); void loadCachedProxyServer(std::function<void(const std::string&)> cb); /** * The TLS settings, used only if tls is chosen as a sip transport. */ void generateDhParams(); void newOutgoingCallHelper(const std::shared_ptr<SIPCall>& call, const Uri& uri); std::shared_ptr<SIPCall> newSwarmOutgoingCallHelper( const Uri& uri, const std::vector<libjami::MediaMap>& mediaList); std::shared_ptr<SIPCall> createSubCall(const std::shared_ptr<SIPCall>& mainCall); std::filesystem::path idPath_ {}; std::filesystem::path cachePath_ {}; std::filesystem::path dataPath_ {}; #if HAVE_RINGNS mutable std::mutex registeredNameMutex_; std::string registeredName_; bool setRegisteredName(const std::string& name) { std::lock_guard<std::mutex> lock(registeredNameMutex_); if (registeredName_ != name) { registeredName_ = name; return true; } return false; } std::string getRegisteredName() const { std::lock_guard<std::mutex> lock(registeredNameMutex_); return registeredName_; } #endif std::shared_ptr<dht::Logger> logger_; std::shared_ptr<dhtnet::tls::CertificateStore> certStore_; std::shared_ptr<dht::DhtRunner> dht_ {}; std::shared_ptr<AccountManager> accountManager_; dht::crypto::Identity id_ {}; mutable std::mutex messageMutex_ {}; std::map<dht::Value::Id, PendingMessage> sentMessages_; dhtnet::fileutils::IdList treatedMessages_; /* tracked buddies presence */ mutable std::mutex buddyInfoMtx; std::map<dht::InfoHash, BuddyInfo> trackedBuddies_; mutable std::mutex dhtValuesMtx_; std::atomic_int syncCnt_ {0}; /** * DHT port actually used. * This holds the actual DHT port, which might different from the port * set in the configuration. This can be the case if UPnP is used. */ in_port_t dhtPortUsed() { return (upnpCtrl_ and dhtUpnpMapping_.isValid()) ? dhtUpnpMapping_.getExternalPort() : config().dhtPort; } /* Current UPNP mapping */ dhtnet::upnp::Mapping dhtUpnpMapping_ {dhtnet::upnp::PortType::UDP}; /** * Proxy */ std::string proxyServerCached_ {}; /** * Optional: via_addr construct from received parameters */ pjsip_host_port via_addr_ {}; pjsip_transport* via_tp_ {nullptr}; mutable std::mutex connManagerMtx_ {}; std::unique_ptr<dhtnet::ConnectionManager> connectionManager_; virtual void updateUpnpController() override; std::mutex discoveryMapMtx_; std::shared_ptr<dht::PeerDiscovery> peerDiscovery_; std::map<dht::InfoHash, DiscoveredPeer> discoveredPeers_; std::map<std::string, std::string> discoveredPeerMap_; std::set<std::shared_ptr<dht::http::Request>> requests_; mutable std::mutex sipConnsMtx_ {}; struct SipConnection { std::shared_ptr<SipTransport> transport; // Needs to keep track of that channel to access underlying ICE // information, as the SipTransport use a generic transport std::shared_ptr<dhtnet::ChannelSocket> channel; }; // NOTE: here we use a vector to avoid race conditions. In fact the contact // can ask for a SIP channel when we are creating a new SIP Channel with this // peer too. std::map<SipConnectionKey, std::vector<SipConnection>> sipConns_; std::mutex pendingCallsMutex_; std::map<DeviceId, std::vector<std::shared_ptr<SIPCall>>> pendingCalls_; std::mutex onConnectionClosedMtx_ {}; std::map<DeviceId, std::function<void(const DeviceId&, bool)>> onConnectionClosed_ {}; /** * onConnectionClosed contains callbacks that need to be called if a sub call is failing * @param deviceId The device we are calling * @param eraseDummy Erase the dummy call (a temporary subcall that must be stop when we will * not create new subcalls) */ void callConnectionClosed(const DeviceId& deviceId, bool eraseDummy); /** * Ask a device to open a channeled SIP socket * @param peerId The contact who owns the device * @param deviceId The device to ask * @param forceNewConnection If we want a new SIP connection * @param pc A pending call to stop if the request fails * @note triggers cacheSIPConnection */ void requestSIPConnection(const std::string& peerId, const DeviceId& deviceId, const std::string& connectionType, bool forceNewConnection = false, const std::shared_ptr<SIPCall>& pc = {}); /** * Store a new SIP connection into sipConnections_ * @param channel The new sip channel * @param peerId The contact who owns the device * @param deviceId Device linked to that transport */ void cacheSIPConnection(std::shared_ptr<dhtnet::ChannelSocket>&& channel, const std::string& peerId, const DeviceId& deviceId); /** * Shutdown a SIP connection * @param channel The channel to close * @param peerId The contact who owns the device * @param deviceId Device linked to that transport */ void shutdownSIPConnection(const std::shared_ptr<dhtnet::ChannelSocket>& channel, const std::string& peerId, const DeviceId& deviceId); void requestMessageConnection(const std::string& peerId, const DeviceId& deviceId, const std::string& connectionType, bool forceNewConnection); // File transfers std::mutex transfersMtx_ {}; std::set<std::string> incomingFileTransfers_ {}; /** * Helper used to send SIP messages on a channeled connection * @param conn The connection used * @param to Peer URI * @param ctx Context passed to the send request * @param token Token used * @param data Message to send * @param cb Callback to trigger when message is sent * @throw runtime_error if connection is invalid * @return if the request will be sent */ bool 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); void onSIPMessageSent(const std::shared_ptr<TextMessageCtx>& ctx, int code); std::mutex gitServersMtx_ {}; std::map<dht::Value::Id, std::unique_ptr<GitServer>> gitServers_ {}; //// File transfer (for profiles) std::shared_ptr<TransferManager> nonSwarmTransferManager_; std::atomic_bool deviceAnnounced_ {false}; std::atomic_bool noSha3sumVerification_ {false}; bool publishPresence_ {true}; std::map<Uri::Scheme, std::unique_ptr<ChannelHandlerInterface>> channelHandlers_ {}; std::unique_ptr<ConversationModule> convModule_; std::mutex moduleMtx_; std::unique_ptr<SyncModule> syncModule_; std::mutex rdvMtx_; int dhtBoundPort_ {0}; void initConnectionManager(); enum class PresenceState : int { DISCONNECTED = 0, AVAILABLE, CONNECTED }; std::map<std::string, PresenceState> presenceState_; std::string presenceNote_; }; static inline std::ostream& operator<<(std::ostream& os, const JamiAccount& acc) { os << "[Account " << acc.getAccountID() << "] "; return os; } } // namespace jami
33,453
C++
.h
756
36.125661
104
0.646968
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
752,023
jamiaccount_config.h
savoirfairelinux_jami-daemon/src/jamidht/jamiaccount_config.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 "sip/sipaccountbase_config.h" namespace jami { constexpr static std::string_view ACCOUNT_TYPE_JAMI = "RING"; constexpr static const char* const DHT_DEFAULT_BOOTSTRAP = "bootstrap.jami.net"; constexpr static const char* DEFAULT_TURN_SERVER = "turn.jami.net"; constexpr static const char* DEFAULT_TURN_USERNAME = "ring"; constexpr static const char* DEFAULT_TURN_PWD = "ring"; constexpr static const char* DEFAULT_TURN_REALM = "ring"; struct JamiAccountConfig : public SipAccountBaseConfig { JamiAccountConfig(const std::string& id = {}, const std::filesystem::path& path = {}) : SipAccountBaseConfig(std::string(ACCOUNT_TYPE_JAMI), id, path) { // Default values specific to Jami accounts hostname = DHT_DEFAULT_BOOTSTRAP; turnServer = DEFAULT_TURN_SERVER; turnServerUserName = DEFAULT_TURN_USERNAME; turnServerPwd = DEFAULT_TURN_PWD; turnServerRealm = DEFAULT_TURN_REALM; turnEnabled = true; upnpEnabled = true; } void serialize(YAML::Emitter& out) const override; void unserialize(const YAML::Node& node) override; std::map<std::string, std::string> toMap() const override; void fromMap(const std::map<std::string, std::string>&) override; std::string deviceName {}; uint16_t dhtPort {0}; bool dhtPeerDiscovery {false}; bool accountPeerDiscovery {false}; bool accountPublish {false}; std::string bootstrapListUrl {"https://config.jami.net/bootstrapList"}; bool proxyEnabled {false}; bool proxyListEnabled {true}; std::string proxyServer {"dhtproxy.jami.net:[80-95]"}; std::string proxyListUrl {"https://config.jami.net/proxyList"}; std::string nameServer {}; std::string registeredName {}; bool allowPeersFromHistory {true}; bool allowPeersFromContact {true}; bool allowPeersFromTrusted {true}; bool allowPublicIncoming {true}; std::string managerUri {}; std::string managerUsername {}; std::string archivePath {"archive.gz"}; bool archiveHasPassword {true}; // not saved, only used client->daemon struct Credentials { std::string archive_password_scheme; std::string archive_password; std::string archive_pin; std::string archive_path; } credentials; std::string receipt {}; std::vector<uint8_t> receiptSignature {}; bool dhtPublicInCalls {true}; }; }
3,139
C++
.h
74
37.878378
89
0.716765
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
752,024
namedirectory.h
savoirfairelinux_jami-daemon/src/jamidht/namedirectory.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 "noncopyable.h" #include <asio/io_context.hpp> #include <functional> #include <map> #include <set> #include <string> #include <mutex> #include <memory> #include <thread> #include <filesystem> namespace dht { class Executor; namespace crypto { struct PublicKey; } namespace http { class Request; struct Response; class Resolver; } // namespace http namespace log { struct Logger; } using Logger = log::Logger; } // namespace dht namespace jami { class Task; class NameDirectory { public: enum class Response : int { found = 0, invalidResponse, notFound, error }; enum class RegistrationResponse : int { success = 0, invalidName, invalidCredentials, alreadyTaken, error, incompleteRequest, signatureVerificationFailed, unsupported }; using LookupCallback = std::function<void(const std::string& result, Response response)>; using SearchResult = std::vector<std::map<std::string, std::string>>; using SearchCallback = std::function<void(const SearchResult& result, Response response)>; using RegistrationCallback = std::function<void(RegistrationResponse response, const std::string& name)>; NameDirectory(const std::string& serverUrl, std::shared_ptr<dht::Logger> l = {}); ~NameDirectory(); void load(); static NameDirectory& instance(const std::string& serverUrl, std::shared_ptr<dht::Logger> l = {}); static NameDirectory& instance(); void setToken(std::string token) { serverToken_ = std::move(token); } static void lookupUri(std::string_view uri, const std::string& default_server, LookupCallback cb); void lookupAddress(const std::string& addr, LookupCallback cb); void lookupName(const std::string& name, LookupCallback cb); bool searchName(const std::string& /*name*/, SearchCallback /*cb*/) { return false; } void registerName(const std::string& addr, const std::string& name, const std::string& owner, RegistrationCallback cb, const std::string& signedname, const std::string& publickey); private: NON_COPYABLE(NameDirectory); NameDirectory(NameDirectory&&) = delete; NameDirectory& operator=(NameDirectory&&) = delete; std::string serverUrl_; std::string serverToken_; std::filesystem::path cachePath_; std::mutex cacheLock_ {}; std::shared_ptr<dht::Logger> logger_; /* * ASIO I/O Context for sockets in httpClient_. * Note: Each context is used in one thread only. */ std::shared_ptr<asio::io_context> httpContext_; std::shared_ptr<dht::http::Resolver> resolver_; std::mutex requestsMtx_ {}; std::set<std::shared_ptr<dht::http::Request>> requests_; std::map<std::string, std::string> pendingRegistrations_ {}; std::map<std::string, std::string> nameCache_ {}; std::map<std::string, std::string> addrCache_ {}; std::weak_ptr<Task> saveTask_; void setHeaderFields(dht::http::Request& request); std::string nameCache(const std::string& addr) { std::lock_guard l(cacheLock_); auto cacheRes = nameCache_.find(addr); return cacheRes != nameCache_.end() ? cacheRes->second : std::string {}; } std::string addrCache(const std::string& name) { std::lock_guard l(cacheLock_); auto cacheRes = addrCache_.find(name); return cacheRes != addrCache_.end() ? cacheRes->second : std::string {}; } bool validateName(const std::string& name) const; static bool verify(const std::string& name, const dht::crypto::PublicKey& publickey, const std::string& signature); void scheduleCacheSave(); void saveCache(); void loadCache(); }; } // namespace jami
4,662
C++
.h
124
31.774194
109
0.670064
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
752,025
archive_account_manager.h
savoirfairelinux_jami-daemon/src/jamidht/archive_account_manager.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 "account_manager.h" namespace jami { class ArchiveAccountManager : public AccountManager { public: using OnExportConfig = std::function<std::map<std::string, std::string>()>; ArchiveAccountManager(const std::filesystem::path& path, OnExportConfig&& onExportConfig, std::string archivePath, const std::string& nameServer) : AccountManager(path, nameServer) , onExportConfig_(std::move(onExportConfig)) , archivePath_(std::move(archivePath)) {} struct ArchiveAccountCredentials : AccountCredentials { in_port_t dhtPort; std::vector<std::string> dhtBootstrap; dht::crypto::Identity updateIdentity; }; void initAuthentication(const std::string& accountId, PrivateKey request, std::string deviceName, std::unique_ptr<AccountCredentials> credentials, AuthSuccessCallback onSuccess, AuthFailureCallback onFailure, const OnChangeCallback& onChange) override; void startSync(const OnNewDeviceCb&, const OnDeviceAnnouncedCb& dcb = {}, bool publishPresence = true) override; bool changePassword(const std::string& password_old, const std::string& password_new) override; virtual std::vector<uint8_t> getPasswordKey(const std::string& /*password*/) override; void syncDevices() override; void addDevice(const std::string& password, AddDeviceCallback) override; bool revokeDevice(const std::string& device, std::string_view scheme, const std::string& password, RevokeDeviceCallback) override; bool exportArchive(const std::string& destinationPath, std::string_view scheme, const std::string& password); bool isPasswordValid(const std::string& password) override; #if HAVE_RINGNS /*void lookupName(const std::string& name, LookupCallback cb) override; void lookupAddress(const std::string& address, LookupCallback cb) override;*/ void registerName(const std::string& name, std::string_view scheme, const std::string& password, RegistrationCallback cb) override; #endif /** * Change the validity of a certificate. If hash is empty, update all certificates */ bool setValidity(std::string_view scheme, const std::string& password, dht::crypto::Identity& device, const dht::InfoHash& id, int64_t validity); private: struct DhtLoadContext; struct AuthContext { std::string accountId; PrivateKey key; CertRequest request; std::string deviceName; std::unique_ptr<ArchiveAccountCredentials> credentials; std::unique_ptr<DhtLoadContext> dhtContext; AuthSuccessCallback onSuccess; AuthFailureCallback onFailure; }; void createAccount(AuthContext& ctx); void migrateAccount(AuthContext& ctx); std::pair<std::string, std::shared_ptr<dht::Value>> makeReceipt( const dht::crypto::Identity& id, const dht::crypto::Certificate& device, const std::string& ethAccount); void updateArchive(AccountArchive& content /*, const ContactList& syncData*/) const; void saveArchive(AccountArchive& content, std::string_view scheme, const std::string& pwd); AccountArchive readArchive(std::string_view scheme, const std::string& password) const; static std::pair<std::vector<uint8_t>, dht::InfoHash> computeKeys(const std::string& password, const std::string& pin, bool previous = false); bool updateCertificates(AccountArchive& archive, dht::crypto::Identity& device); static bool needsMigration(const dht::crypto::Identity& id); void loadFromFile(AuthContext& ctx); void loadFromDHT(const std::shared_ptr<AuthContext>& ctx); void onArchiveLoaded(AuthContext& ctx, AccountArchive&& a); OnExportConfig onExportConfig_; std::string archivePath_; }; } // namespace jami
5,039
C++
.h
102
39.686275
116
0.66111
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
752,026
sync_module.h
savoirfairelinux_jami-daemon/src/jamidht/sync_module.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 "jamidht/jamiaccount.h" namespace jami { class SyncModule { public: SyncModule(std::weak_ptr<JamiAccount>&& account); ~SyncModule() = default; /** * Store a new Sync connection * @param socket The new sync channel * @param peerId The contact who owns the device * @param deviceId Device linked to that transport */ void cacheSyncConnection(std::shared_ptr<dhtnet::ChannelSocket>&& socket, const std::string& peerId, const DeviceId& deviceId); bool isConnected(const DeviceId& deviceId) const; /** * Send sync to all connected devices * @param syncMsg Default message * @param deviceId If we need to filter on a device */ void syncWithConnected(const std::shared_ptr<SyncMsg>& syncMsg = nullptr, const DeviceId& deviceId = {}); private: class Impl; std::shared_ptr<Impl> pimpl_; }; } // namespace jami
1,704
C++
.h
45
33.288889
109
0.691283
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
752,027
transfer_channel_handler.h
savoirfairelinux_jami-daemon/src/jamidht/transfer_channel_handler.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 "jamidht/channel_handler.h" #include "jamidht/jamiaccount.h" #include <dhtnet/connectionmanager.h> namespace jami { /** * Manages Conversation's channels */ class TransferChannelHandler : public ChannelHandlerInterface { public: TransferChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm); ~TransferChannelHandler(); /** * Ask for a new channel * This replaces the connectDevice() in jamiaccount * @param deviceId The device to connect * @param channelName The name of the channel * @param cb The callback to call when connected (can be immediate if already connected) */ void connect(const DeviceId& deviceId, const std::string& channelName, ConnectCb&& cb) override; /** * Determine if we accept or not the request * @param deviceId device who asked * @param name name asked * @return if we accept or not */ bool onRequest(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name) override; /** * Handle socket ready * @param deviceId Related device * @param name Name of the handler * @param channel Channel to handle */ void onReady(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) override; private: std::weak_ptr<JamiAccount> account_; dhtnet::ConnectionManager& connectionManager_; std::filesystem::path idPath_; }; } // namespace jami
2,338
C++
.h
59
35.525424
108
0.701893
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
752,028
Common.h
savoirfairelinux_jami-daemon/src/jamidht/eth/libdevcore/Common.h
/* 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.h * @author Gav Wood <i@gavwood.com> * @date 2014 * * Very common stuff (i.e. that every other header needs except vector_ref.h). */ #pragma once // way too many unsigned to size_t warnings in 32 bit build #ifdef _M_IX86 #pragma warning(disable : 4244) #endif #if _MSC_VER && _MSC_VER < 1900 #define _ALLOW_KEYWORD_MACROS #define noexcept throw() #endif #ifdef __INTEL_COMPILER #pragma warning(disable : 3682) // call through incomplete class #endif #include <map> #include <unordered_map> #include <vector> #include <set> #include <unordered_set> #include <functional> #include <string> #include <chrono> #include "vector_ref.h" // Quote a given token stream to turn it into a string. #define DEV_QUOTED_HELPER(s) #s #define DEV_QUOTED(s) DEV_QUOTED_HELPER(s) #define DEV_IGNORE_EXCEPTIONS(X) \ try { \ X; \ } catch (...) { \ } #define DEV_IF_THROWS(X) \ try { \ X; \ } catch (...) namespace dev { extern char const* Version; extern std::string const EmptyString; // Binary data types. using bytes = std::vector<uint8_t>; using bytesRef = vector_ref<uint8_t>; using bytesConstRef = vector_ref<uint8_t const>; // Map types. using StringMap = std::map<std::string, std::string>; using BytesMap = std::map<bytes, bytes>; using HexMap = std::map<bytes, bytes>; // Hash types. using StringHashMap = std::unordered_map<std::string, std::string>; // String types. using strings = std::vector<std::string>; // Fixed-length string types. using string32 = std::array<char, 32>; /// @returns the absolute distance between _a and _b. template<class N> inline N diff(N const& _a, N const& _b) { return std::max(_a, _b) - std::min(_a, _b); } /// RAII utility class whose destructor calls a given function. class ScopeGuard { public: ScopeGuard(std::function<void(void)> _f) : m_f(_f) {} ~ScopeGuard() { m_f(); } private: std::function<void(void)> m_f; }; #ifdef _MSC_VER // TODO. #define DEV_UNUSED #else #define DEV_UNUSED __attribute__((unused)) #endif enum class WithExisting : int { Trust = 0, Verify, Rescue, Kill }; } // namespace dev
2,841
C++
.h
95
27.452632
78
0.708931
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
752,030
FixedHash.h
savoirfairelinux_jami-daemon/src/jamidht/eth/libdevcore/FixedHash.h
/* 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 FixedHash.h * @author Gav Wood <i@gavwood.com> * @date 2014 * * The FixedHash fixed-size "hash" container type. */ #pragma once #include <array> #include <cstdint> #include <algorithm> #include <random> #include <opendht/rng.h> #include "CommonData.h" namespace dev { /// Compile-time calculation of Log2 of constant values. template<unsigned N> struct StaticLog2 { enum { result = 1 + StaticLog2<N / 2>::result }; }; template<> struct StaticLog2<1> { enum { result = 0 }; }; /// Fixed-size raw-byte array container type, with an API optimised for storing hashes. /// Transparently converts to/from the corresponding arithmetic type; this will /// assume the data contained in the hash is big-endian. template<unsigned N> class FixedHash { public: /// The size of the container. enum { size = N }; /// A dummy flag to avoid accidental construction from pointer. enum ConstructFromPointerType { ConstructFromPointer }; /// Method to convert from a string. enum ConstructFromStringType { FromHex, FromBinary }; /// Method to convert from a string. enum ConstructFromHashType { AlignLeft, AlignRight, FailIfDifferent }; /// Construct an empty hash. FixedHash() { m_data.fill(0); } /// Construct from another hash, filling with zeroes or cropping as necessary. template<unsigned M> explicit FixedHash(FixedHash<M> const& _h, ConstructFromHashType _t = AlignLeft) { m_data.fill(0); unsigned c = std::min(M, N); for (unsigned i = 0; i < c; ++i) m_data[_t == AlignRight ? N - 1 - i : i] = _h[_t == AlignRight ? M - 1 - i : i]; } /// Convert from unsigned explicit FixedHash(unsigned _u) { toBigEndian(_u, m_data); } /// Explicitly construct, copying from a byte array. explicit FixedHash(bytes const& _b, ConstructFromHashType _t = FailIfDifferent) { if (_b.size() == N) memcpy(m_data.data(), _b.data(), std::min<unsigned>(_b.size(), N)); else { m_data.fill(0); if (_t != FailIfDifferent) { auto c = std::min<unsigned>(_b.size(), N); for (unsigned i = 0; i < c; ++i) m_data[_t == AlignRight ? N - 1 - i : i] = _b[_t == AlignRight ? _b.size() - 1 - i : i]; } } } /// Explicitly construct, copying from a byte array. explicit FixedHash(bytesConstRef _b, ConstructFromHashType _t = FailIfDifferent) { if (_b.size() == N) memcpy(m_data.data(), _b.data(), std::min<unsigned>(_b.size(), N)); else { m_data.fill(0); if (_t != FailIfDifferent) { auto c = std::min<unsigned>(_b.size(), N); for (unsigned i = 0; i < c; ++i) m_data[_t == AlignRight ? N - 1 - i : i] = _b[_t == AlignRight ? _b.size() - 1 - i : i]; } } } /// Explicitly construct, copying from a bytes in memory with given pointer. explicit FixedHash(uint8_t const* _bs, ConstructFromPointerType) { memcpy(m_data.data(), _bs, N); } /// Explicitly construct, copying from a string. explicit FixedHash(std::string const& _s, ConstructFromStringType _t = FromHex, ConstructFromHashType _ht = FailIfDifferent) : FixedHash(_t == FromHex ? fromHex(_s, WhenError::Throw) : dev::asBytes(_s), _ht) {} /// @returns true iff this is the empty hash. explicit operator bool() const { return std::any_of(m_data.begin(), m_data.end(), [](uint8_t _b) { return _b != 0; }); } // The obvious comparison operators. bool operator==(FixedHash const& _c) const { return m_data == _c.m_data; } bool operator!=(FixedHash const& _c) const { return m_data != _c.m_data; } bool operator<(FixedHash const& _c) const { for (unsigned i = 0; i < N; ++i) if (m_data[i] < _c.m_data[i]) return true; else if (m_data[i] > _c.m_data[i]) return false; return false; } bool operator>=(FixedHash const& _c) const { return !operator<(_c); } bool operator<=(FixedHash const& _c) const { return operator==(_c) || operator<(_c); } bool operator>(FixedHash const& _c) const { return !operator<=(_c); } // The obvious binary operators. FixedHash& operator^=(FixedHash const& _c) { for (unsigned i = 0; i < N; ++i) m_data[i] ^= _c.m_data[i]; return *this; } FixedHash operator^(FixedHash const& _c) const { return FixedHash(*this) ^= _c; } FixedHash& operator|=(FixedHash const& _c) { for (unsigned i = 0; i < N; ++i) m_data[i] |= _c.m_data[i]; return *this; } FixedHash operator|(FixedHash const& _c) const { return FixedHash(*this) |= _c; } FixedHash& operator&=(FixedHash const& _c) { for (unsigned i = 0; i < N; ++i) m_data[i] &= _c.m_data[i]; return *this; } FixedHash operator&(FixedHash const& _c) const { return FixedHash(*this) &= _c; } FixedHash operator~() const { FixedHash ret; for (unsigned i = 0; i < N; ++i) ret[i] = ~m_data[i]; return ret; } // Big-endian increment. FixedHash& operator++() { for (unsigned i = size; i > 0 && !++m_data[--i];) { } return *this; } /// @returns true if all one-bits in @a _c are set in this object. bool contains(FixedHash const& _c) const { return (*this & _c) == _c; } /// @returns a particular byte from the hash. uint8_t& operator[](unsigned _i) { return m_data[_i]; } /// @returns a particular byte from the hash. uint8_t operator[](unsigned _i) const { return m_data[_i]; } /// @returns an abridged version of the hash as a user-readable hex string. std::string abridged() const { return toHex(ref().cropped(0, 4)) + "\342\200\246"; } /// @returns a version of the hash as a user-readable hex string that leaves out the middle part. std::string abridgedMiddle() const { return toHex(ref().cropped(0, 4)) + "\342\200\246" + toHex(ref().cropped(N - 4)); } /// @returns the hash as a user-readable hex string. std::string hex() const { return toHex(ref()); } /// @returns a mutable byte vector_ref to the object's data. bytesRef ref() { return bytesRef(m_data.data(), N); } /// @returns a constant byte vector_ref to the object's data. bytesConstRef ref() const { return bytesConstRef(m_data.data(), N); } /// @returns a mutable byte pointer to the object's data. uint8_t* data() { return m_data.data(); } /// @returns a constant byte pointer to the object's data. uint8_t const* data() const { return m_data.data(); } /// @returns begin iterator. auto begin() const -> typename std::array<uint8_t, N>::const_iterator { return m_data.begin(); } /// @returns end iterator. auto end() const -> typename std::array<uint8_t, N>::const_iterator { return m_data.end(); } /// @returns a copy of the object's data as a byte vector. bytes asBytes() const { return bytes(data(), data() + N); } /// @returns a mutable reference to the object's data as an STL array. std::array<uint8_t, N>& asArray() { return m_data; } /// @returns a constant reference to the object's data as an STL array. std::array<uint8_t, N> const& asArray() const { return m_data; } /// Populate with random data. template<class Engine> void randomize(Engine& _eng) { for (auto& i : m_data) i = (uint8_t) std::uniform_int_distribution<uint16_t>(0, 255)(_eng); } /// @returns a random valued object. static FixedHash random() { FixedHash ret; std::random_device rd; ret.randomize(rd); return ret; } template<unsigned P, unsigned M> inline FixedHash& shiftBloom(FixedHash<M> const& _h) { return (*this |= _h.template bloomPart<P, N>()); } template<unsigned P, unsigned M> inline bool containsBloom(FixedHash<M> const& _h) { return contains(_h.template bloomPart<P, N>()); } template<unsigned P, unsigned M> inline FixedHash<M> bloomPart() const { unsigned const c_bloomBits = M * 8; unsigned const c_mask = c_bloomBits - 1; unsigned const c_bloomBytes = (StaticLog2<c_bloomBits>::result + 7) / 8; static_assert((M & (M - 1)) == 0, "M must be power-of-two"); static_assert(P * c_bloomBytes <= N, "out of range"); FixedHash<M> ret; uint8_t const* p = data(); for (unsigned i = 0; i < P; ++i) { unsigned index = 0; for (unsigned j = 0; j < c_bloomBytes; ++j, ++p) index = (index << 8) | *p; index &= c_mask; ret[M - 1 - index / 8] |= (1 << (index % 8)); } return ret; } /// Returns the index of the first bit set to one, or size() * 8 if no bits are set. inline unsigned firstBitSet() const { unsigned ret = 0; for (auto d : m_data) if (d) for (;; ++ret, d <<= 1) if (d & 0x80) return ret; else { } else ret += 8; return ret; } void clear() { m_data.fill(0); } private: std::array<uint8_t, N> m_data; ///< The binary data. }; template<unsigned T> class SecureFixedHash : private FixedHash<T> { public: using ConstructFromHashType = typename FixedHash<T>::ConstructFromHashType; using ConstructFromStringType = typename FixedHash<T>::ConstructFromStringType; using ConstructFromPointerType = typename FixedHash<T>::ConstructFromPointerType; SecureFixedHash() = default; explicit SecureFixedHash(bytes const& _b, ConstructFromHashType _t = FixedHash<T>::FailIfDifferent) : FixedHash<T>(_b, _t) {} explicit SecureFixedHash(bytesConstRef _b, ConstructFromHashType _t = FixedHash<T>::FailIfDifferent) : FixedHash<T>(_b, _t) {} template<unsigned M> explicit SecureFixedHash(FixedHash<M> const& _h, ConstructFromHashType _t = FixedHash<T>::AlignLeft) : FixedHash<T>(_h, _t) {} SecureFixedHash(SecureFixedHash<T> const& _h) : FixedHash<T>(_h.makeInsecure()) {} template<unsigned M> explicit SecureFixedHash(SecureFixedHash<M> const& _h, ConstructFromHashType _t = FixedHash<T>::AlignLeft) : FixedHash<T>(_h.makeInsecure(), _t) {} explicit SecureFixedHash(std::string const& _s, ConstructFromStringType _t = FixedHash<T>::FromHex, ConstructFromHashType _ht = FixedHash<T>::FailIfDifferent) : FixedHash<T>(_s, _t, _ht) {} explicit SecureFixedHash(bytes const* _d, ConstructFromPointerType _t) : FixedHash<T>(_d, _t) {} ~SecureFixedHash() { ref().cleanse(); } SecureFixedHash<T>& operator=(SecureFixedHash<T> const& _c) { if (&_c == this) return *this; ref().cleanse(); FixedHash<T>::operator=(static_cast<FixedHash<T> const&>(_c)); return *this; } using FixedHash<T>::size; FixedHash<T> const& makeInsecure() const { return static_cast<FixedHash<T> const&>(*this); } FixedHash<T>& writable() { clear(); return static_cast<FixedHash<T>&>(*this); } using FixedHash<T>::operator bool; // The obvious comparison operators. bool operator==(SecureFixedHash const& _c) const { return static_cast<FixedHash<T> const&>(*this).operator==( static_cast<FixedHash<T> const&>(_c)); } bool operator!=(SecureFixedHash const& _c) const { return static_cast<FixedHash<T> const&>(*this).operator!=( static_cast<FixedHash<T> const&>(_c)); } bool operator<(SecureFixedHash const& _c) const { return static_cast<FixedHash<T> const&>(*this).operator<( static_cast<FixedHash<T> const&>(_c)); } bool operator>=(SecureFixedHash const& _c) const { return static_cast<FixedHash<T> const&>(*this).operator>=( static_cast<FixedHash<T> const&>(_c)); } bool operator<=(SecureFixedHash const& _c) const { return static_cast<FixedHash<T> const&>(*this).operator<=( static_cast<FixedHash<T> const&>(_c)); } bool operator>(SecureFixedHash const& _c) const { return static_cast<FixedHash<T> const&>(*this).operator>( static_cast<FixedHash<T> const&>(_c)); } using FixedHash<T>::operator==; using FixedHash<T>::operator!=; using FixedHash<T>::operator<; using FixedHash<T>::operator>=; using FixedHash<T>::operator<=; using FixedHash<T>::operator>; // The obvious binary operators. SecureFixedHash& operator^=(FixedHash<T> const& _c) { static_cast<FixedHash<T>&>(*this).operator^=(_c); return *this; } SecureFixedHash operator^(FixedHash<T> const& _c) const { return SecureFixedHash(*this) ^= _c; } SecureFixedHash& operator|=(FixedHash<T> const& _c) { static_cast<FixedHash<T>&>(*this).operator^=(_c); return *this; } SecureFixedHash operator|(FixedHash<T> const& _c) const { return SecureFixedHash(*this) |= _c; } SecureFixedHash& operator&=(FixedHash<T> const& _c) { static_cast<FixedHash<T>&>(*this).operator^=(_c); return *this; } SecureFixedHash operator&(FixedHash<T> const& _c) const { return SecureFixedHash(*this) &= _c; } SecureFixedHash& operator^=(SecureFixedHash const& _c) { static_cast<FixedHash<T>&>(*this).operator^=(static_cast<FixedHash<T> const&>(_c)); return *this; } SecureFixedHash operator^(SecureFixedHash const& _c) const { return SecureFixedHash(*this) ^= _c; } SecureFixedHash& operator|=(SecureFixedHash const& _c) { static_cast<FixedHash<T>&>(*this).operator^=(static_cast<FixedHash<T> const&>(_c)); return *this; } SecureFixedHash operator|(SecureFixedHash const& _c) const { return SecureFixedHash(*this) |= _c; } SecureFixedHash& operator&=(SecureFixedHash const& _c) { static_cast<FixedHash<T>&>(*this).operator^=(static_cast<FixedHash<T> const&>(_c)); return *this; } SecureFixedHash operator&(SecureFixedHash const& _c) const { return SecureFixedHash(*this) &= _c; } SecureFixedHash operator~() const { auto r = ~static_cast<FixedHash<T> const&>(*this); return static_cast<SecureFixedHash const&>(r); } using FixedHash<T>::abridged; using FixedHash<T>::abridgedMiddle; bytesConstRef ref() const { return FixedHash<T>::ref(); } uint8_t const* data() const { return FixedHash<T>::data(); } static SecureFixedHash<T> random() { SecureFixedHash<T> ret; std::random_device rd; ret.randomize(rd); return ret; } using FixedHash<T>::firstBitSet; void clear() { ref().cleanse(); } }; /// Fast equality operator for h256. template<> inline bool FixedHash<32>::operator==(FixedHash<32> const& _other) const { const uint64_t* hash1 = (const uint64_t*) data(); const uint64_t* hash2 = (const uint64_t*) _other.data(); return (hash1[0] == hash2[0]) && (hash1[1] == hash2[1]) && (hash1[2] == hash2[2]) && (hash1[3] == hash2[3]); } // Common types of FixedHash. using h2048 = FixedHash<256>; using h1024 = FixedHash<128>; using h520 = FixedHash<65>; using h512 = FixedHash<64>; using h256 = FixedHash<32>; using h160 = FixedHash<20>; using h128 = FixedHash<16>; using h64 = FixedHash<8>; using h512s = std::vector<h512>; using h256s = std::vector<h256>; using h160s = std::vector<h160>; using h256Set = std::set<h256>; using h160Set = std::set<h160>; using h256Hash = std::unordered_set<h256>; using h160Hash = std::unordered_set<h160>; /// Convert the given value into h160 (160-bit unsigned integer) using the right 20 bytes. inline h160 right160(h256 const& _t) { h160 ret; memcpy(ret.data(), _t.data() + 12, 20); return ret; } } // namespace dev
17,218
C++
.h
450
31.431111
101
0.605484
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
752,032
Address.h
savoirfairelinux_jami-daemon/src/jamidht/eth/libdevcore/Address.h
/* 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 /// This file defined Address alias for FixedHash of 160 bits and some /// special Address constants. #pragma once #include "FixedHash.h" namespace dev { /// An Ethereum address: 20 bytes. /// @NOTE This is not endian-specific; it's just a bunch of bytes. using Address = h160; /// A vector of Ethereum addresses. using Addresses = h160s; /// A hash set of Ethereum addresses. using AddressHash = std::unordered_set<h160>; } // namespace dev
1,157
C++
.h
27
39.851852
73
0.75
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
752,033
SHA3.h
savoirfairelinux_jami-daemon/src/jamidht/eth/libdevcore/SHA3.h
/* 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 SHA3.h * @author Gav Wood <i@gavwood.com> * @date 2014 * * The FixedHash fixed-size "hash" container type. */ #pragma once #include <string> #include "FixedHash.h" #include "vector_ref.h" namespace dev { // SHA-3 convenience routines. /// Calculate SHA3-256 hash of the given input and load it into the given output. /// @returns false if o_output.size() != 32. bool sha3(bytesConstRef _input, bytesRef o_output); /// Calculate SHA3-256 hash of the given input, returning as a 256-bit hash. inline h256 sha3(bytesConstRef _input) { h256 ret; sha3(_input, ret.ref()); return ret; } /// Calculate SHA3-256 hash of the given input, returning as a 256-bit hash. inline h256 sha3(bytes const& _input) { return sha3(bytesConstRef(&_input)); } /// Calculate SHA3-256 hash of the given input (presented as a binary-filled string), returning as a /// 256-bit hash. inline h256 sha3(std::string const& _input) { return sha3(bytesConstRef(_input)); } /// Calculate SHA3-256 hash of the given input (presented as a FixedHash), returns a 256-bit hash. template<unsigned N> inline h256 sha3(FixedHash<N> const& _input) { return sha3(_input.ref()); } /// Calculate SHA3-256 hash of the given input, possibly interpreting it as nibbles, and return the /// hash as a string filled with binary data. inline std::string sha3(std::string const& _input, bool _isNibbles) { return asString((_isNibbles ? sha3(fromHex(_input)) : sha3(bytesConstRef(&_input))).asBytes()); } } // namespace dev
2,221
C++
.h
64
32.28125
100
0.737751
savoirfairelinux/jami-daemon
144
47
2
GPL-3.0
9/20/2024, 9:42:05 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
752,034
Common.h
savoirfairelinux_jami-daemon/src/jamidht/eth/libdevcrypto/Common.h
/* 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.h * @author Alex Leverington <nessence@gmail.com> * @author Gav Wood <i@gavwood.com> * @date 2014 * * Ethereum-specific data structures & algorithms. */ #pragma once #include <mutex> #include <libdevcore/Address.h> #include <libdevcore/Common.h> #include <libdevcore/FixedHash.h> namespace dev { using Secret = SecureFixedHash<32>; /// A public key: 64 bytes. /// @NOTE This is not endian-specific; it's just a bunch of bytes. using Public = h512; /// A signature: 65 bytes: r: [0, 32), s: [32, 64), v: 64. /// @NOTE This is not endian-specific; it's just a bunch of bytes. using Signature = h520; struct SignatureStruct { SignatureStruct() = default; SignatureStruct(Signature const& _s) { *(h520*) this = _s; } SignatureStruct(h256 const& _r, h256 const& _s, uint8_t _v) : r(_r) , s(_s) , v(_v) {} operator Signature() const { return *(h520 const*) this; } /// @returns true if r,s,v values are valid, otherwise false bool isValid() const noexcept; h256 r; h256 s; uint8_t v = 0; }; /// A vector of secrets. using Secrets = std::vector<Secret>; /// Convert a secret key into the public key equivalent. Public toPublic(Secret const& _secret); /// Convert a public key to address. Address toAddress(Public const& _public); /// Convert a secret key into address of public key equivalent. /// @returns 0 if it's not a valid secret key. Address toAddress(Secret const& _secret); /// Simple class that represents a "key pair". /// All of the data of the class can be regenerated from the secret key (m_secret) alone. /// Actually stores a tuplet of secret, public and address (the right 160-bits of the public). class KeyPair { public: KeyPair() = default; /// Normal constructor - populates object from the given secret key. /// If the secret key is invalid the constructor succeeds, but public key /// and address stay "null". KeyPair(Secret const& _sec); /// Create a new, randomly generated object. static KeyPair create(); /// Create from an encrypted seed. // static KeyPair fromEncryptedSeed(bytesConstRef _seed, std::string const& _password); Secret const& secret() const { return m_secret; } /// Retrieve the public key. Public const& pub() const { return m_public; } /// Retrieve the associated address of the public key. Address const& address() const { return m_address; } bool operator==(KeyPair const& _c) const { return m_public == _c.m_public; } bool operator!=(KeyPair const& _c) const { return m_public != _c.m_public; } private: Secret m_secret; Public m_public; Address m_address; }; namespace crypto { class InvalidState : public std::runtime_error { public: InvalidState() : runtime_error("invalid state") {}; }; class CryptoException : public std::runtime_error { public: CryptoException(const char* err) : runtime_error(err) {}; }; } // namespace crypto } // namespace dev
3,703
C++
.h
100
33.61
94
0.703497
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
752,035
swarm_manager.h
savoirfairelinux_jami-daemon/src/jamidht/swarm/swarm_manager.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 "routing_table.h" #include "swarm_protocol.h" #include <iostream> #include <memory> namespace jami { using namespace swarm_protocol; class SwarmManager : public std::enable_shared_from_this<SwarmManager> { using ChannelCb = std::function<bool(const std::shared_ptr<dhtnet::ChannelSocketInterface>&)>; using NeedSocketCb = std::function<void(const std::string&, ChannelCb&&)>; using ToConnectCb = std::function<bool(const NodeId&)>; using OnConnectionChanged = std::function<void(bool ok)>; public: explicit SwarmManager(const NodeId&, const std::mt19937_64& rand, ToConnectCb&& toConnectCb); ~SwarmManager(); NeedSocketCb needSocketCb_; std::weak_ptr<SwarmManager> weak() { return weak_from_this(); } /** * Get swarm manager id * @return NodeId */ const NodeId& getId() const { return id_; } /** * Set list of nodes to the routing table known_nodes * @param known_nodes * @return if some are new */ bool setKnownNodes(const std::vector<NodeId>& known_nodes); /** * Set list of nodes to the routing table mobile_nodes * @param mobile_nodes */ void setMobileNodes(const std::vector<NodeId>& mobile_nodes); /** * Add channel to routing table * @param channel */ void addChannel(const std::shared_ptr<dhtnet::ChannelSocketInterface>& channel); /** * Remove channel from routing table * @param channel */ void removeNode(const NodeId& nodeId); /** * Change mobility of specific node * @param nodeId * @param isMobile */ void changeMobility(const NodeId& nodeId, bool isMobile); /** * get all nodes from the different tables in bucket */ std::vector<NodeId> getAllNodes() const; /** * Delete nodes from the different tables in bucket */ void deleteNode(std::vector<NodeId> nodes); // For tests /** * Get routing table * @return RoutingTable */ RoutingTable& getRoutingTable() { return routing_table; }; /** * Get buckets of routing table * @return buckets list */ std::list<Bucket>& getBuckets() { return routing_table.getBuckets(); }; /** * Shutdown swarm manager */ void shutdown(); /** * Restart the swarm manager. * * This function must be called in situations where we want * to use a swarm manager that was previously shut down. */ void restart(); /** * Display swarm manager info */ void display() { JAMI_DEBUG("SwarmManager {:s} has {:d} nodes in table [P = {}]", getId().to_c_str(), routing_table.getRoutingTableNodeCount(), isMobile_); // print nodes of routingtable for (auto& bucket : routing_table.getBuckets()) { for (auto& node : bucket.getNodes()) { JAMI_DEBUG("Node {:s}", node.first.toString()); } } } /* * Callback for connection changed * @param cb */ void onConnectionChanged(OnConnectionChanged cb) { onConnectionChanged_ = std::move(cb); } /** * Set mobility of swarm manager * @param isMobile */ void setMobility(bool isMobile) { isMobile_ = isMobile; } /** * Get mobility of swarm manager * @return true if mobile, false if not */ bool isMobile() const { return isMobile_; } /** * Maintain/Update buckets * @param toConnect Nodes to connect */ void maintainBuckets(const std::set<NodeId>& toConnect = {}); /** * Check if we're connected with a specific device * @param deviceId * @return true if connected, false if not */ bool isConnectedWith(const NodeId& deviceId); /** * Check if swarm manager is shutdown * @return true if shutdown, false if not */ bool isShutdown() { return isShutdown_; }; private: /** * Add node to the known_nodes list * @param nodeId * @return if node inserted */ bool addKnownNode(const NodeId& nodeId); /** * Add node to the mobile_Nodes list * @param nodeId */ void addMobileNodes(const NodeId& nodeId); /** * Send nodes request to fill known_nodes list * @param socket * @param nodeId * @param q * @param numberNodes */ void sendRequest(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, NodeId& nodeId, Query q, int numberNodes = Bucket::BUCKET_MAX_SIZE); /** * Send answer to request * @param socket * @param msg */ void sendAnswer(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, const Message& msg_); /** * Interpret received message * @param socket */ void receiveMessage(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket); /** * Reset node's timer expiry * @param ec * @param socket * @param node */ void resetNodeExpiry(const asio::error_code& ec, const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket, NodeId node = {}); /** * Try to establich connexion with specific node * @param nodeId */ void tryConnect(const NodeId& nodeId); /** * Remove node from routing table * @param nodeId */ void removeNodeInternal(const NodeId& nodeId); const NodeId id_; bool isMobile_ {false}; std::mt19937_64 rd; mutable std::mutex mutex; RoutingTable routing_table; std::atomic_bool isShutdown_ {false}; OnConnectionChanged onConnectionChanged_ {}; ToConnectCb toConnectCb_; }; } // namespace jami
6,553
C++
.h
206
25.786408
104
0.637171
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
752,036
swarm_protocol.h
savoirfairelinux_jami-daemon/src/jamidht/swarm/swarm_protocol.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 <string> #include <string_view> #include <msgpack.hpp> #include <opendht/infohash.h> using namespace std::literals; using NodeId = dht::h256; namespace jami { namespace swarm_protocol { static constexpr int version = 1; enum class Query : uint8_t { FIND = 1, FOUND = 2 }; using NodeId = dht::PkId; struct Request { Query q; // Type of query int num; // Number of nodes NodeId nodeId; MSGPACK_DEFINE_MAP(q, num, nodeId); }; struct Response { Query q; std::vector<NodeId> nodes; std::vector<NodeId> mobile_nodes; MSGPACK_DEFINE_MAP(q, nodes, mobile_nodes); }; struct Message { int v = version; bool is_mobile {false}; std::optional<Request> request; std::optional<Response> response; MSGPACK_DEFINE_MAP(v, is_mobile, request, response); }; }; // namespace swarm_protocol } // namespace jami MSGPACK_ADD_ENUM(jami::swarm_protocol::Query);
1,641
C++
.h
53
28.433962
73
0.728717
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
752,037
swarm_channel_handler.h
savoirfairelinux_jami-daemon/src/jamidht/swarm/swarm_channel_handler.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 "jamidht/channel_handler.h" #include "jamidht/conversation_channel_handler.h" #include <dhtnet/multiplexed_socket.h> #include "logger.h" namespace jami { using NodeId = dht::h256; class JamiAccount; /** * Manages Conversation's channels */ class SwarmChannelHandler : public ChannelHandlerInterface { public: SwarmChannelHandler(const std::shared_ptr<JamiAccount>& acc, dhtnet::ConnectionManager& cm); ~SwarmChannelHandler(); #ifdef LIBJAMI_TESTABLE std::atomic_bool disableSwarmManager {false}; #endif /** * Ask for a new git channel * @param nodeId The node to connect * @param name The name of the channel * @param cb The callback to call when connected (can be immediate if already connected) */ void connect(const NodeId& nodeId, const std::string& name, ConnectCb&& cb) override; /** * Determine if we accept or not the git request * @param nodeId node who asked * @param name name asked * @return if the channel is for a valid conversation and node not banned */ bool onRequest(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name) override; /** * TODO, this needs to extract gitservers from JamiAccount */ void onReady(const std::shared_ptr<dht::crypto::Certificate>& peer, const std::string& name, std::shared_ptr<dhtnet::ChannelSocket> channel) override; private: std::weak_ptr<JamiAccount> account_; dhtnet::ConnectionManager& connectionManager_; }; } // namespace jami
2,355
C++
.h
61
34.57377
103
0.706965
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
752,038
routing_table.h
savoirfairelinux_jami-daemon/src/jamidht/swarm/routing_table.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 "manager.h" #include <dhtnet/multiplexed_socket.h> #include <opendht/infohash.h> #include <asio.hpp> #include <asio/detail/deadline_timer_service.hpp> #include <vector> #include <memory> #include <list> #include <set> #include <algorithm> using NodeId = dht::PkId; namespace jami { static constexpr const std::chrono::minutes FIND_PERIOD {10}; struct NodeInfo { bool isMobile_ {false}; std::shared_ptr<dhtnet::ChannelSocketInterface> socket {}; asio::steady_timer refresh_timer {*Manager::instance().ioContext(), FIND_PERIOD}; NodeInfo() = delete; NodeInfo(NodeInfo&&) = default; NodeInfo(std::shared_ptr<dhtnet::ChannelSocketInterface> socket_) : socket(socket_) {} NodeInfo(bool mobile, std::shared_ptr<dhtnet::ChannelSocketInterface> socket_) : isMobile_(mobile) , socket(socket_) {} }; class Bucket { public: static constexpr int BUCKET_MAX_SIZE = 2; Bucket() = delete; Bucket(const Bucket&) = delete; Bucket(const NodeId&); /** * Add Node socket to bucket * @param socket * @return true if node was added, false if not */ bool addNode(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket); /** * Add NodeInfo to bucket * @param nodeInfo * @return true if node was added, false if not */ bool addNode(NodeInfo&& info); /** * Remove NodeId socket from bucket and insert it in known_nodes or * mobile_nodes depending on its type * @param nodeId * @return true if node was removed, false if not */ bool removeNode(const NodeId& nodeId); /** * Get connected nodes from bucket * @return map of NodeId and NodeInfo */ std::map<NodeId, NodeInfo>& getNodes() { return nodes; } /** * Get NodeIds from bucket * @return set of NodeIds */ std::set<NodeId> getNodeIds() const; /** * Test if socket exists in nodes * @param nodeId * @return true if node exists, false if not */ bool hasNode(const NodeId& nodeId) const; /** * Add NodeId to known_nodes if it doesn't exist in nodes * @param nodeId * @return true if known node was added, false if not */ bool addKnownNode(const NodeId& nodeId); /** * Remove NodeId from known_nodes * @param nodeId */ void removeKnownNode(const NodeId& nodeId) { known_nodes.erase(nodeId); } /** * Get NodeIds from known_nodes * @return set of known NodeIds */ const std::set<NodeId>& getKnownNodes() const { return known_nodes; } /** * Returns NodeId from known_nodes at index * @param index * @return NodeId */ NodeId getKnownNode(unsigned index) const; /** * Test if NodeId exist in known_nodes * @param nodeId * @return true if known node exists, false if not */ bool hasKnownNode(const NodeId& nodeId) const { return known_nodes.find(nodeId) != known_nodes.end(); } /** * Add NodeId to mobile_nodes if it doesn't exist in nodes * @param nodeId * @return true if mobile node was added, false if not */ bool addMobileNode(const NodeId& nodeId); /** * Remove NodeId from mobile_nodes * @param nodeId */ void removeMobileNode(const NodeId& nodeId) { mobile_nodes.erase(nodeId); } /** * Test if NodeId exist in mobile_nodes * @param nodeId * @return true if mobile node exists, false if not */ bool hasMobileNode(const NodeId& nodeId) { return mobile_nodes.find(nodeId) != mobile_nodes.end(); } /** * Get NodeIds from mobile_nodes * @return set of mobile NodeIds */ const std::set<NodeId>& getMobileNodes() const { return mobile_nodes; } /** * Add NodeId to connecting_nodes if it doesn't exist in nodes * @param nodeId * @param nodeInfo * @return true if connecting node was added, false if not */ bool addConnectingNode(const NodeId& nodeId); /** * Remove NodeId from connecting_nodes * @param nodeId */ void removeConnectingNode(const NodeId& nodeId) { connecting_nodes.erase(nodeId); } /** Get NodeIds of connecting_nodes * @return set of connecting NodeIds */ const std::set<NodeId>& getConnectingNodes() const { return connecting_nodes; }; /** * Test if NodeId exist in connecting_nodes * @param nodeId * @return true if connecting node exists, false if not */ bool hasConnectingNode(const NodeId& nodeId) const { return connecting_nodes.find(nodeId) != connecting_nodes.end(); } bool isEmpty() const { return nodes.empty(); } /** * Indicate if bucket is full * @return true if bucket is full, false if not */ bool isFull() const { return nodes.size() == BUCKET_MAX_SIZE; }; /** * Returns random numberNodes NodeId from known_nodes * @param numberNodes * @param rd * @return set of numberNodes random known NodeIds */ std::set<NodeId> getKnownNodesRandom(unsigned numberNodes, std::mt19937_64& rd) const; /** * Returns random NodeId from known_nodes * @param rd * @return random known NodeId */ NodeId randomId(std::mt19937_64& rd) const { auto node = getKnownNodesRandom(1, rd); return *node.begin(); } /** * Returns socket's timer * @param socket * @return timer */ asio::steady_timer& getNodeTimer(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket); /** * Shutdowns socket and removes it from nodes. * The corresponding node is moved to known_nodes or mobile_nodes * @param socket * @return true if node was shutdown, false if not found */ bool shutdownNode(const NodeId& nodeId); /** * Shutdowns all sockets in nodes through shutdownNode */ void shutdownAllNodes(); /** * Prints bucket and bucket's number */ void printBucket(unsigned number) const; /** * Change mobility of specific node, mobile or not */ void changeMobility(const NodeId& nodeId, bool isMobile); /** * Returns number of nodes in bucket * @return size of nodes */ unsigned getNodesSize() const { return nodes.size(); } /** * Returns number of knwon_nodes in bucket * @return size of knwon_nodes */ unsigned getKnownNodesSize() const { return known_nodes.size(); } /** * Returns number of mobile_nodes in bucket * @return size of mobile_nodes */ unsigned getConnectingNodesSize() const { return connecting_nodes.size(); } /** * Returns bucket lower limit * @return NodeId lower limit */ NodeId getLowerLimit() const { return lowerLimit_; }; /** * Set bucket's lower limit * @param nodeId */ void setLowerLimit(const NodeId& nodeId) { lowerLimit_ = nodeId; } // For tests /** * Get sockets from bucket * @return set of sockets */ std::set<std::shared_ptr<dhtnet::ChannelSocketInterface>> getNodeSockets() const; private: NodeId lowerLimit_; std::map<NodeId, NodeInfo> nodes; std::set<NodeId> known_nodes; std::set<NodeId> connecting_nodes; std::set<NodeId> mobile_nodes; mutable std::mutex mutex; }; // #################################################################################################### class RoutingTable { public: RoutingTable(); /** * Add socket to bucket * @param socket * @return true if socket was added, false if not */ bool addNode(const std::shared_ptr<dhtnet::ChannelSocketInterface>& socket); /** * Add socket to specific bucket * @param channel * @param bucket * @return true if socket was added to bucket, false if not */ bool addNode(const std::shared_ptr<dhtnet::ChannelSocketInterface>& channel, std::list<Bucket>::iterator& bucket); /** * Removes node from routing table * Adds it to known_nodes or mobile_nodes depending on mobility * @param socket * @return true if node was removed, false if not */ bool removeNode(const NodeId& nodeId); /** * Check if connected node exsits in routing table * @param nodeId * @return true if node exists, false if not */ bool hasNode(const NodeId& nodeId); /** * Add known node to routing table * @param nodeId * @return true if known node was added, false if not */ bool addKnownNode(const NodeId& nodeId); /** * Checks if known node exists in routing table * @param nodeId * @return true if known node exists, false if not */ bool hasKnownNode(const NodeId& nodeId) const { auto bucket = findBucket(nodeId); return bucket->hasKnownNode(nodeId); } /** * Add mobile node to routing table * @param nodeId * @return true if mobile node was added, false if not */ bool addMobileNode(const NodeId& nodeId); /** * Remove mobile node to routing table * @param nodeId * @return true if mobile node was removed, false if not */ void removeMobileNode(const NodeId& nodeId); /** * Check if mobile node exists in routing table * @param nodeId * @return true if mobile node exists, false if not */ bool hasMobileNode(const NodeId& nodeId); /** * Add connecting node to routing table * @param nodeId * @return true if connecting node was added, false if not */ bool addConnectingNode(const NodeId& nodeId); /** * Remove connecting connecting node to routing table * @param nodeId * @return true if connecting node was removed, false if not */ void removeConnectingNode(const NodeId& nodeId); /** * Check if Connecting node exists in routing table * @param nodeId * @return true if connecting node exists, false if not */ bool hasConnectingNode(const NodeId& nodeId) const { auto bucket = findBucket(nodeId); return bucket->hasConnectingNode(nodeId); } /** * Returns bucket iterator containing nodeId * @param nodeId * @return bucket iterator */ std::list<Bucket>::iterator findBucket(const NodeId& nodeId); /** * Returns bucket iterator containing nodeId * @param nodeId * @return bucket iterator */ inline const std::list<Bucket>::const_iterator findBucket(const NodeId& nodeId) const { return std::list<Bucket>::const_iterator( const_cast<RoutingTable*>(this)->findBucket(nodeId)); } /** * Returns the count closest nodes to a specific nodeId * @param nodeId * @param count * @return vector of nodeIds */ std::vector<NodeId> closestNodes(const NodeId& nodeId, unsigned count); /** * Returns number of buckets in routing table * @return size of buckets */ unsigned getRoutingTableSize() const { return buckets.size(); } /** * Returns number of total nodes in routing table * @return size of nodes */ unsigned getRoutingTableNodeCount() const { size_t count = 0; for (const auto& b : buckets) count += b.getNodesSize(); return count; } /** * Prints routing table */ void printRoutingTable() const; /** * Shutdowns a node * @param nodeId */ void shutdownNode(const NodeId& nodeId); /** * Shutdowns all nodes in routing table and add them to known_nodes or mobile_nodes */ void shutdownAllNodes() { for (auto& bucket : buckets) bucket.shutdownAllNodes(); } /** * Sets id for routing table * @param node */ void setId(const NodeId& node) { id_ = node; } /** * Returns id for routing table * @return Nodeid */ NodeId getId() const { return id_; } /** * Returns buckets in routing table * @return list buckets */ std::list<Bucket>& getBuckets() { return buckets; } /** * Returns all routing table's connected nodes * @return vector of nodeIds */ std::vector<NodeId> getNodes() const; /** * Returns all routing table's known nodes *@return vector of nodeIds */ std::vector<NodeId> getKnownNodes() const; /** * Returns all routing table's mobile nodes * @return vector of nodeIds */ std::vector<NodeId> getMobileNodes() const; /** * Returns all routing table's connecting nodes * @return vector of nodeIds */ std::vector<NodeId> getConnectingNodes() const; /** * Returns mobile nodes corresponding to the swarm's id * @return vector of nodeIds */ std::vector<NodeId> getBucketMobileNodes() const; /** * Test if connected nodeId is in specific bucket * @param it * @param nodeId * @return true if nodeId is in bucket, false if not */ bool contains(const std::list<Bucket>::iterator& it, const NodeId& nodeId) const; /** * Return every node from each bucket */ std::vector<NodeId> getAllNodes() const; /** * Delete node from every table in bucket */ void deleteNode(const NodeId& nodeId); private: RoutingTable(const RoutingTable&) = delete; RoutingTable& operator=(const RoutingTable&) = delete; /** * Returns middle of routing table * @param it * @return NodeId */ NodeId middle(std::list<Bucket>::iterator& it) const; /** * Returns depth of routing table * @param bucket * @return depth */ unsigned depth(std::list<Bucket>::iterator& bucket) const; /** * Splits bucket * @param bucket * @return true if bucket was split, false if not */ bool split(std::list<Bucket>::iterator& bucket); NodeId id_; std::list<Bucket> buckets; mutable std::mutex mutex_; }; }; // namespace jami
14,855
C++
.h
480
25.4
103
0.642822
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
752,039
message_engine.h
savoirfairelinux_jami-daemon/src/im/message_engine.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 <string> #include <map> #include <set> #include <chrono> #include <mutex> #include <cstdint> #include <filesystem> #include <msgpack.hpp> #include <asio/steady_timer.hpp> namespace jami { class SIPAccountBase; namespace im { using MessageToken = uint64_t; enum class MessageStatus { UNKNOWN=0, IDLE, SENDING, SENT, FAILURE }; class MessageEngine { public: MessageEngine(SIPAccountBase&, const std::filesystem::path& path); /** * Add a message to the engine and try to send it * @param to Uri of the peer * @param deviceId (Optional) if we want to send to a specific device * @param payloads The message * @param refreshToken The token of the message */ MessageToken sendMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t refreshToken); MessageStatus getStatus(MessageToken t) const; void onMessageSent(const std::string& peer, MessageToken t, bool success, const std::string& deviceId = {}); /** * @TODO change MessageEngine by a queue, * @NOTE retryOnTimeout is used for failing SIP messages (jamiAccount::sendTextMessage) */ void onPeerOnline(const std::string& peer, const std::string& deviceId = {}, bool retryOnTimeout = true); /** * Load persisted messages */ void load(); /** * Persist messages */ void save() const; private: static const constexpr unsigned MAX_RETRIES = 20; using clock = std::chrono::system_clock; void retrySend(const std::string& peer, const std::string& deviceId, bool retryOnTimeout); void save_() const; void scheduleSave(); struct Message { MessageToken token {}; std::string to {}; std::map<std::string, std::string> payloads {}; MessageStatus status {MessageStatus::IDLE}; unsigned retried {0}; clock::time_point last_op {}; MSGPACK_DEFINE_MAP(token, to, payloads, status, retried, last_op) }; SIPAccountBase& account_; const std::filesystem::path savePath_; std::shared_ptr<asio::io_context> ioContext_; asio::steady_timer saveTimer_; std::map<std::string, std::list<Message>> messages_; std::map<std::string, std::list<Message>> messagesDevices_; mutable std::mutex messagesMutex_ {}; }; } // namespace im } // namespace jami MSGPACK_ADD_ENUM(jami::im::MessageStatus);
3,423
C++
.h
95
29.747368
91
0.650726
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
752,040
instant_messaging.h
savoirfairelinux_jami-daemon/src/im/instant_messaging.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 <string> #include <vector> #include <map> #include <list> #include <stdexcept> #ifdef HAVE_CONFIG_H #include "config.h" #endif extern "C" { struct pjsip_inv_session; struct pjsip_rx_data; struct pjsip_msg; struct pjsip_tx_data; } namespace jami { namespace im { struct InstantMessageException : std::runtime_error { InstantMessageException(const std::string& str = "") : std::runtime_error("InstantMessageException occurred: " + str) {} }; /** * Constructs and sends a SIP message. * * The expected format of the map key is: * type/subtype[; *[; arg=value]] * eg: "text/plain; id=1234;part=2;of=1001" * note: all whitespace is optional * * If the map contains more than one pair, then a multipart/mixed message type will be created * containing multiple message parts. Note that all of the message parts must be able to fit into * one message... they will not be split into multiple messages. * * @param session SIP session * @param payloads a map where the mime type and optional parameters are the key * and the message payload is the value * * Exception: throw InstantMessageException if no message sent */ void sendSipMessage(pjsip_inv_session* session, const std::map<std::string, std::string>& payloads); /** * 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> parseSipMessage(const pjsip_msg* msg); void fillPJSIPMessageBody(pjsip_tx_data& tdata, const std::map<std::string, std::string>& payloads); } // namespace im } // namespace jami
2,500
C++
.h
70
33.8
100
0.739777
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
752,041
pluginsutils.h
savoirfairelinux_jami-daemon/src/plugin/pluginsutils.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 <json/json.h> #include <opendht/crypto.h> #include <map> #include <vector> #include <filesystem> namespace jami { /** * @namespace PluginUtils * @brief This namespace provides auxiliary functions to the Plugin System. * Specially to the JamiPluginManager class. * Those functions were originally part of the latter class, but for * code clarity purposes, they were moved. */ namespace PluginUtils { /** * @brief Returns complete manifest.json file path given a installation path. * @param rootPath */ std::filesystem::path manifestPath(const std::filesystem::path& rootPath); /** * @brief Returns installation path given a plugin's library path. * @param soPath */ std::filesystem::path getRootPathFromSoPath(const std::filesystem::path& soPath); /** * @brief Returns data path given a plugin's library path. * @param pluginSoPath */ std::filesystem::path dataPath(const std::filesystem::path& pluginSoPath); /** * @brief Check if manifest.json has minimum format and parses its content * to a map<string, string>. * @param root * @return Maps with manifest.json content if success. */ std::map<std::string, std::string> checkManifestJsonContentValidity(const Json::Value& root); /** * @brief Reads manifest.json stream and checks if it's valid. * @param stream * @return Maps with manifest.json content if success. */ std::map<std::string, std::string> checkManifestValidity(std::istream& stream); /** * @brief Recives manifest.json file contents, and checks its validity. * @param vec * @return Maps with manifest.json content if success. */ std::map<std::string, std::string> checkManifestValidity(const std::vector<uint8_t>& vec); /** * @brief Returns a map with platform information. * @return Map with platform information */ std::map<std::string, std::string> getPlatformInfo(); /** * @brief Parses the manifest file of an installed plugin if it's valid. * @param manifestFilePath * @return Map with manifest contents */ std::map<std::string, std::string> parseManifestFile(const std::filesystem::path& manifestFilePath, const std::string& rootPath); /** * @brief Parses the manifest file of an installed plugin if it's valid. * @param rootPath * @param manifestFile * @return Map with manifest contents */ std::string parseManifestTranslation(const std::string& rootPath, std::ifstream& manifestFile); /** * @brief Validates a plugin based on its manifest.json file. * @param rootPath * @return True if valid */ bool checkPluginValidity(const std::filesystem::path& rootPath); /** * @brief Reads the manifest file content without uncompressing the whole archive and * return a map with manifest contents if success. * @param jplPath * @return Map with manifest contents */ std::map<std::string, std::string> readPluginManifestFromArchive(const std::string& jplPath); /** * @brief Read the plugin's certificate * @param rootPath * @param pluginId * @return Certificate object pointer */ std::unique_ptr<dht::crypto::Certificate> readPluginCertificate(const std::string& rootPath, const std::string& pluginId); /** * @brief Read plugin certificate without uncompressing the whole archive.and * return an object Certificate * @param jplPath * @return Certificate object pointer */ std::unique_ptr<dht::crypto::Certificate> readPluginCertificateFromArchive(const std::string& jplPath); /** * @brief Reads signature file content without uncompressing the whole archive and * @param jplPath * return a map of signature path as key and signature content as value. */ std::map<std::string, std::vector<uint8_t>> readPluginSignatureFromArchive(const std::string& jplPath); /** * @brief Read the signature of the file signature without uncompressing the whole archive. * @param jplPath * @return Signature file content */ std::vector<uint8_t> readSignatureFileFromArchive(const std::string& jplPath); /** * @brief Function used by archiver to extract files from plugin jpl to the plugin * installation path. * @param relativeFileName * @return Pair <bool, string> meaning if file should be extracted and where to. */ std::pair<bool, std::string_view> uncompressJplFunction(std::string_view relativeFileName); /** * @brief Returns the language of the current locale. * @return language */ std::string getLanguage(); /** * @brief Returns the available keys and translations for a given plugin. * If the locale is not available, return the english default. * @param rootPath * @param lang * @return locales map */ std::map<std::string, std::string> getLocales(const std::string& rootPath, const std::string& lang); /** * @brief Returns the available keys and translations for a given file. * If the locale is not available, return empty map. * @param localeFilePath * @return locales map */ std::map<std::string, std::string> processLocaleFile(const std::string& localeFilePath); } // namespace PluginUtils } // namespace jami
5,718
C++
.h
152
35.493421
129
0.754193
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
752,042
webviewservicesmanager.h
savoirfairelinux_jami-daemon/src/plugin/webviewservicesmanager.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/>. */ // adapted from ChatServicesManager #pragma once #include "noncopyable.h" #include "webviewhandler.h" #include <list> #include <memory> #include <map> #include <mutex> #include <vector> #include <string> namespace jami { class PluginManager; using WebViewHandlerPtr = std::unique_ptr<WebViewHandler>; /** * @brief This class provides the interface between loaded WebViewHandlers * and client webviews. */ class WebViewServicesManager { public: /** * @brief Registers the WebViewHandler services with the PluginManager, * allows for loading/unloading, and interaction with client webviews * @param pluginManager */ WebViewServicesManager(PluginManager& pluginManager); NON_COPYABLE(WebViewServicesManager); /** * @brief Transmits a message from the client's webview to the plugin * @param pluginId * @param webViewId * @param messageId * @param payload The message itself */ void sendWebViewMessage(const std::string& pluginId, const std::string& webViewId, const std::string& messageId, const std::string& payload); /** * @brief Transmits an attach event from the client's webview to the plugin * @param pluginId * @param accountId * @param webViewId * @param action The reason why the webview was created * @returns a relative path to an HTML file inside the datapath */ std::string sendWebViewAttach(const std::string& pluginId, const std::string& accountId, const std::string& webViewId, const std::string& action); /** * @brief Transmits a detach event from the client's webview to the plugin * @param pluginId * @param webViewId */ void sendWebViewDetach(const std::string& pluginId, const std::string& webViewId); private: /** * @brief Registers the WebViewHandler services with the PluginManager * @param pluginManager */ void registerComponentsLifeCycleManagers(PluginManager& pluginManager); /** * @brief Exposes services that aren't related to life cycle management * @param pluginManager */ void registerWebViewService(PluginManager& pluginManager); /** * @brief Get the webview handler for a specified plugin * @return A WebViewHandler pointer */ WebViewHandler* getWebViewHandlerPointer(const std::string& pluginId); /** * @brief map of all registered handlers, pluginId -> HandlerPtr */ std::map<std::string, WebViewHandlerPtr> handlersIdMap {}; }; } // namespace jami
3,432
C++
.h
94
30.755319
86
0.688835
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
752,043
preferencehandler.h
savoirfairelinux_jami-daemon/src/plugin/preferencehandler.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 <string> #include <map> namespace jami { /** * @brief This abstract class is an API we need to implement from plugin side. * In other words, a plugin functionality that handles preferences per account * must start from the implementation of this class. */ class PreferenceHandler { public: virtual ~PreferenceHandler() {} /** * @brief Returns a map with handler's name, iconPath, and pluginId. */ virtual std::map<std::string, std::string> getHandlerDetails() = 0; /** * @brief If a preference can have different values depending on accountId, those values should * be stored in the plugin through this function. * @param accountId * @param key * @param value */ virtual void setPreferenceAttribute(const std::string& accountId, const std::string& key, const std::string& value) = 0; /** * @brief If a preference can be stored as per accountId, this function should return True. * @param key * @return True if preference can be changed through setPreferenceAttribute method. */ virtual bool preferenceMapHasKey(const std::string& key) = 0; /** * @brief Reset stored preferences for given accountId. * @param accountId */ virtual void resetPreferenceAttributes(const std::string& accountId) = 0; /** * @brief Returns the dataPath of the plugin that created this PreferenceHandler. */ std::string id() const { return id_; } /** * @brief Should be called by the PreferenceHandler creator to set the plugins id_ variable. */ virtual void setId(const std::string& id) final { id_ = id; } private: // Is the dataPath of the plugin that created this ChatHandler. std::string id_; }; } // namespace jami
2,592
C++
.h
68
33.117647
99
0.686555
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
752,044
webviewmessage.h
savoirfairelinux_jami-daemon/src/plugin/webviewmessage.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 <string> namespace jami { /** * @struct WebViewMessage * @brief Contains data about a web view message * Used by WebViewServicesManager. Passed from a plugin to the daemon. After that, this struct is no * longer used. */ struct WebViewMessage { // Which webview is this message about const std::string webViewId; // Message identifier const std::string messageId; // The actual message itself. Can be a path, JSON, XML, or anything, // as long as it fits in a string const std::string payload; }; } // namespace jami
1,292
C++
.h
36
33.472222
100
0.738228
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
752,045
preferenceservicesmanager.h
savoirfairelinux_jami-daemon/src/plugin/preferenceservicesmanager.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 "preferencehandler.h" #include "noncopyable.h" #include <list> #include <map> #include <tuple> #include <memory> #include <vector> namespace jami { class PluginManager; using PreferenceHandlerPtr = std::unique_ptr<PreferenceHandler>; /** * @brief This class provides the interface between PreferenceHandlers * and per account preferences. Besides, it stores pointers to all loaded PreferenceHandlers; */ class PreferenceServicesManager { public: /** * @brief Constructor registers PreferenceHandler API services to the PluginManager * instance. These services will store PreferenceHandler pointers or clean them * from the Plugin System once a plugin is loaded or unloaded. * @param pluginManager */ PreferenceServicesManager(PluginManager& pluginManager); ~PreferenceServicesManager(); NON_COPYABLE(PreferenceServicesManager); /** * @brief List all PreferenceHandlers available. * @return Vector with stored PreferenceHandlers pointers. */ std::vector<std::string> getHandlers() const; /** * @brief Returns details Map from s implementation. * @param preferenceHandlerIdStr * @return Details map from the PreferenceHandler implementation */ std::map<std::string, std::string> getHandlerDetails( const std::string& preferenceHandlerIdStr) const; /** * @brief Sets a preference. * @param key * @param value * @param rootPath * @param accountId * @return False if preference was changed. */ bool setPreference(const std::string& key, const std::string& value, const std::string& rootPath, const std::string& accountId); /** * @brief Resets acc preferences to default values. * @param rootPath * @param accountId */ void resetPreferences(const std::string& rootPath, const std::string& accountId); private: /** * @brief Exposes PreferenceHandlers' life cycle managers services to the main API. * @param pluginManager */ void registerComponentsLifeCycleManagers(PluginManager& pluginManager); // Components that a plugin can register through registerPreferenceHandler service. std::list<PreferenceHandlerPtr> handlers_; }; } // namespace jami
3,067
C++
.h
83
32.289157
93
0.719771
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
752,046
jamiplugin.h
savoirfairelinux_jami-daemon/src/plugin/jamiplugin.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 <inttypes.h> #ifdef __cplusplus #define EXTERNAL_C_LINKAGE extern "C" // clang-format off #define C_INTERFACE_START EXTERNAL_C_LINKAGE { #define C_INTERFACE_END } // clang-format on #else #define C_LINKAGE #define C_INTERFACE_START #define C_INTERFACE_END #endif #define JAMI_PLUGIN_ABI_VERSION 1 // 0 doesn't exist, considered as error // JAMI_PLUGIN_API_VERSION reflects changes in Services Managers // (CallServicesManager, ChatServicesMansge, and PreferenceServicesManagers) and in JAMI_PluginAPI. #define JAMI_PLUGIN_API_VERSION 2 // 0 doesn't exist, considered as error C_INTERFACE_START; /** * @struct JAMI_PluginVersion * @brief Contains ABI and API versions */ typedef struct JAMI_PluginVersion { // Plugin is not loadable if this number differs from th one // stored in the plugin loader uint32_t abi; // A difference in API number may be acceptable, see the loader code uint32_t api; } JAMI_PluginVersion; struct JAMI_PluginAPI; /** * @struct JAMI_PluginObjectParams * @brief JAMI_PluginCreateFunc parameter */ typedef struct JAMI_PluginObjectParams { const JAMI_PluginAPI* pluginApi; // this API const char* type; } JAMI_PluginObjectParams; // Function that may be implemented by plugin and called by daemon typedef void* (*JAMI_PluginCreateFunc)(JAMI_PluginObjectParams* params, void* closure); // Function that destroys a JAMI_PluginCreateFunc instance typedef void (*JAMI_PluginDestroyFunc)(void* object, void* closure); /** * @struct JAMI_PluginObjectFactory * @brief This structure is filled by plugin. * JAMI_PluginAPI.registerObjectFactory data */ typedef struct JAMI_PluginObjectFactory { JAMI_PluginVersion version; void* closure; // closure for create JAMI_PluginCreateFunc create; JAMI_PluginDestroyFunc destroy; } JAMI_PluginObjectFactory; // Plugins exposed API prototype typedef int32_t (*JAMI_PluginFunc)(const JAMI_PluginAPI* api, const char* name, void* data); /** * @struct JAMI_PluginAPI * @brief This structure is filled by the PluginManager. */ typedef struct JAMI_PluginAPI { JAMI_PluginVersion version; // Structure version, always the first data void* context; // Opaque structure used by next functions // API usable by plugin implementors JAMI_PluginFunc registerObjectFactory; JAMI_PluginFunc invokeService; JAMI_PluginFunc manageComponent; } JAMI_PluginAPI; // Plugins destruction function prototype typedef void (*JAMI_PluginExitFunc)(void); // Plugins main function prototype typedef JAMI_PluginExitFunc (*JAMI_PluginInitFunc)(const JAMI_PluginAPI* api); C_INTERFACE_END; #define JAMI_DYN_INIT_FUNC_NAME "JAMI_dynPluginInit" // Main function expected name #define JAMI_PLUGIN_INIT_STATIC(fname, pname) JAMI_PLUGIN_INIT(fname, pname) #define JAMI_PLUGIN_INIT_DYNAMIC(pname) JAMI_PLUGIN_INIT(JAMI_dynPluginInit, pname) /* Define here platform dependent way to export a declaration x to the dynamic * loading system. */ /* Default case (like POSIX/.so) */ #define JAMI_PLUGIN_INIT(fname, pname) \ (EXTERNAL_C_LINKAGE JAMI_PluginExitFunc fname(const JAMI_PluginAPI* pname)) #define JAMI_PLUGIN_EXIT(fname) (EXTERNAL_C_LINKAGE void fname(void))
3,962
C++
.h
102
36.637255
99
0.76895
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
752,047
pluginloader.h
savoirfairelinux_jami-daemon/src/plugin/pluginloader.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 "jamiplugin.h" #include <dlfcn.h> #include <string> #include <memory> namespace jami { /** * @class Plugin * @brief This class is used to attempt loading a plugin library. */ class Plugin { public: virtual ~Plugin() = default; /** * @brief Load plugin's library. * @return DLPlugin if success. */ static Plugin* load(const std::string& path, std::string& error); virtual void* getSymbol(const char* name) const = 0; /** * @brief Search loaded library for its initialization function * @return Plugin's initialization function. */ virtual JAMI_PluginInitFunc getInitFunction() const { return reinterpret_cast<JAMI_PluginInitFunc>(getSymbol(JAMI_DYN_INIT_FUNC_NAME)); } protected: Plugin() = default; }; /** * @class DLPlugin * @brief This class is used after a plugin library is successfully loaded. */ class DLPlugin : public Plugin { public: DLPlugin(void* handle, const std::string& path) : handle_(handle, ::dlclose) , path_ {path} { api_.context = this; } virtual ~DLPlugin() { unload(); } /** * @brief Unload plugin's library. * @return True if success. */ bool unload() { if (!handle_) { return false; } return !(::dlclose(handle_.release())); } /** * @brief Searchs for symbol in library. * @param name * @return symbol. */ void* getSymbol(const char* name) const { if (!handle_) return nullptr; return ::dlsym(handle_.get(), name); } const std::string& getPath() const { return path_; } public: void* apiContext_; JAMI_PluginAPI api_; private: // Pointer to the loaded library returned by dlopen std::unique_ptr<void, int (*)(void*)> handle_; // Plugin's data path const std::string path_; }; } // namespace jami
2,655
C++
.h
94
23.957447
89
0.659073
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
752,048
pluginpreferencesutils.h
savoirfairelinux_jami-daemon/src/plugin/pluginpreferencesutils.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 <json/json.h> #include <string> #include <set> #include <filesystem> namespace jami { using ChatHandlerList = std::map<std::pair<std::string, std::string>, std::map<std::string, bool>>; /** * @class PluginPreferencesUtils * @brief Static class that gathers functions to manage * plugins' preferences. */ class PluginPreferencesUtils { public: /** * @brief Given a plugin installation path, returns the path to the * preference.json of this plugin. * @param rootPath * @param accountId * @return preference.json file path. */ static std::filesystem::path getPreferencesConfigFilePath(const std::filesystem::path& rootPath, const std::string& accountId = ""); /** * @brief Given a plugin installation path, returns the path to the * preference.msgpack file. * The preference.msgpack file saves the actuall preferences values * if they were modified. * @param rootPath * @param accountId * @return preference.msgpack file path. */ static std::filesystem::path valuesFilePath(const std::filesystem::path& rootPath, const std::string& accountId = ""); /** * @brief Returns the path to allowdeny.msgpack file. * The allowdeny.msgpack file persists ChatHandlers status for each * conversation this handler was previously (de)activated. * @return allowdeny.msgpack file path. */ static std::filesystem::path getAllowDenyListsPath(); /** * @brief Returns a colon separated string with values from a json::Value containing an array. * @param jsonArray * @return Colon separated string with jsonArray contents. */ static std::string convertArrayToString(const Json::Value& jsonArray); /** * @brief Parses a single preference from json::Value to a Map<string, string>. * @param jsonPreference * @return std::map<std::string, std::string> preference */ static std::map<std::string, std::string> parsePreferenceConfig( const Json::Value& jsonPreference); /** * @brief Reads a preference.json file from the plugin installed in rootPath. * @param rootPath * @param accountId * @return std::vector<std::map<std::string, std::string>> with preferences.json content */ static std::vector<std::map<std::string, std::string>> getPreferences( const std::filesystem::path& rootPath, const std::string& accountId = ""); /** * @brief Reads preferences values which were modified from defaultValue * @param rootPath * @param accountId * @return Map with preference keys and actuall values. */ static std::map<std::string, std::string> getUserPreferencesValuesMap( const std::filesystem::path& rootPath, const std::string& accountId = ""); /** * @brief Reads preferences values * @param rootPath * @param accountId * @return Map with preference keys and actuall values. */ static std::map<std::string, std::string> getPreferencesValuesMap( const std::filesystem::path& rootPath, const std::string& accountId = ""); /** * @brief Resets all preferences values to their defaultValues * by erasing all data saved in preferences.msgpack. * @param rootPath * @param accountId * @return True if preferences were reset. */ static bool resetPreferencesValuesMap(const std::string& rootPath, const std::string& accountId); /** * @brief Saves ChantHandlers status provided by list. * @param [in] list */ static void setAllowDenyListPreferences(const ChatHandlerList& list); /** * @brief Reads ChantHandlers status from allowdeny.msgpack file. * @param [out] list */ static void getAllowDenyListPreferences(ChatHandlerList& list); /** * @brief Creates a "always" preference for a handler if this preference doesn't exist yet. * A "always" preference tells the Plugin System if in the event of a new call or chat message, * the handler is suposed to be automatically activated. * @param handlerName * @param rootPath */ static void addAlwaysHandlerPreference(const std::string& handlerName, const std::string& rootPath); /** * @brief Read plugin's preferences and returns wheter a specific handler * "always" preference is True or False. * @param rootPath * @param handlerName * @param accountId * @return True if the handler should be automatically toggled */ static bool getAlwaysPreference(const std::string& rootPath, const std::string& handlerName, const std::string& accountId); private: PluginPreferencesUtils() {} ~PluginPreferencesUtils() {} }; } // namespace jami
5,679
C++
.h
138
34.934783
101
0.678313
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
752,049
mediahandler.h
savoirfairelinux_jami-daemon/src/plugin/mediahandler.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 "streamdata.h" #include "observer.h" #include <string> #include <memory> #include <map> extern "C" { struct AVFrame; } namespace jami { using avSubjectPtr = std::shared_ptr<Observable<AVFrame*>>; /** * @class MediaHandler * @brief It's the base object of the CallMediaHandler */ class MediaHandler { public: virtual ~MediaHandler() = default; /** * @brief Returns the dataPath of the plugin that created this MediaHandler. */ std::string id() const { return id_; } /** * @brief Should be called by the MediaHandler creator to set the plugins id_ variable * with dataPath. */ virtual void setId(const std::string& id) final { id_ = id; } private: // Must be set with plugin's dataPath. std::string id_; }; /** * @class CallMediaHandler * @brief This abstract class is an API we need to implement from plugin side. * In other words, a plugin functionality that plays with audio or video, must start * from the implementation of this class. */ class CallMediaHandler : public MediaHandler { public: /** * @brief Should attach a AVSubject (Observable) to the plugin data process (Observer). * @param data * @param subject */ virtual void notifyAVFrameSubject(const StreamData& data, avSubjectPtr subject) = 0; /** * @brief Should return a map with handler's name, iconPath, pluginId, attached, and dataType. * Daemon expects: * "attached" -> 1 if handler is attached; * "dataType" -> 1 if data processed is video; * "dataType" -> 0 if data processed is audio; * @return Map with CallMediaHandler details. */ virtual std::map<std::string, std::string> getCallMediaHandlerDetails() = 0; /** * @brief Should detach the plugin data process (Observer). */ virtual void detach() = 0; /** * @brief If a preference can be changed without the need to reload the plugin, it * should be done through this function. * @param key * @param value */ virtual void setPreferenceAttribute(const std::string& key, const std::string& value) = 0; /** * @brief If a preference can be changed without the need to reload the plugin, this function * should return True. * @param key * @return True if preference can be changed through setPreferenceAttribute method. */ virtual bool preferenceMapHasKey(const std::string& key) = 0; }; } // namespace jami
3,210
C++
.h
92
31.228261
98
0.697809
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
752,050
callservicesmanager.h
savoirfairelinux_jami-daemon/src/plugin/callservicesmanager.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 "mediahandler.h" #include "streamdata.h" #include "noncopyable.h" #include <list> #include <map> #include <tuple> namespace jami { class PluginManager; using CallMediaHandlerPtr = std::unique_ptr<CallMediaHandler>; using AVSubjectSPtr = std::weak_ptr<Observable<AVFrame*>>; /** * @brief This class provides the interface between loaded MediaHandlers * and call's audio/video streams. Besides it: * (1) stores pointers to all loaded MediaHandlers; * (2) stores pointers to available streams subjects, and; * (3) lists MediaHandler state with respect to each call. In other words, * for a given call, we store if a MediaHandler is active or not. */ class CallServicesManager { public: /** * @brief Constructor registers MediaHandler API services to the PluginManager * instance. These services will store MediaHandler pointers or clean them * from the Plugin System once a plugin is loaded or unloaded. * @param pluginManager */ CallServicesManager(PluginManager& pluginManager); ~CallServicesManager(); NON_COPYABLE(CallServicesManager); /** * @brief Stores a AV stream subject with StreamData properties. During the storage process, * if a MediaHandler is supposed to be activated for the call to which the subject is * related, the activation function is called. * @param data * @param subject */ void createAVSubject(const StreamData& data, AVSubjectSPtr subject); /** * @brief Clears all stream subjects related to the callId. * @param callId */ void clearAVSubject(const std::string& callId); /** * @brief List all MediaHandlers available. * @return Vector with stored MediaHandlers pointers. */ std::vector<std::string> getCallMediaHandlers(); /** * @brief (De)Activates a given MediaHandler to a given call. * If the MediaHandler receives video frames from a hardware decoder, * we need to restart the sender to unlink our encoder and decoder. * When we deactivate a MediaHandler, we try to relink the encoder * and decoder by restarting the sender. * * @param mediaHandlerId * @param callId * @param toggle notify with new subjects if true, detach if false. */ void toggleCallMediaHandler(const std::string& mediaHandlerId, const std::string& callId, const bool toggle); /** * @brief Returns details Map from MediaHandler implementation. * @param mediaHandlerIdStr * @return Details map from the MediaHandler implementation */ std::map<std::string, std::string> getCallMediaHandlerDetails( const std::string& mediaHandlerIdStr); /** * @brief Returns a list of active MediaHandlers for a given call. * @param callId * @return Vector with active MediaHandler ids for a given call. */ std::vector<std::string> getCallMediaHandlerStatus(const std::string& callId); /** * @brief Sets a preference that may be changed while MediaHandler is active. * @param key * @param value * @param rootPath * @return False if preference was changed. */ bool setPreference(const std::string& key, const std::string& value, const std::string& rootPath); /** * @brief Removes call from mediaHandlerToggled_ mapping. * @param callId */ void clearCallHandlerMaps(const std::string& callId); private: /** * @brief Exposes MediaHandlers' life cycle managers services to the main API. * @param pluginManager */ void registerComponentsLifeCycleManagers(PluginManager& pluginManager); /** * @brief Calls MediaHandler API function that attaches a data process to the given * AV stream. * @param callMediaHandlerPtr * @param data * @param subject */ void notifyAVSubject(CallMediaHandlerPtr& callMediaHandlerPtr, const StreamData& data, AVSubjectSPtr& subject); void toggleCallMediaHandler(const uintptr_t mediaHandlerId, const std::string& callId, const bool toggle); /** * @brief Checks if the MediaHandler being (de)activated expects a video stream. * It's used to reduce restartSender call. * @param mediaHandler * @return True if a MediaHandler expects a video stream. */ bool isVideoType(const CallMediaHandlerPtr& mediaHandler); /** * @brief Checks if the MediaHandler was properly attached to a AV stream. * It's used to avoid saving wrong MediaHandler status. * @param mediaHandler * @return True if a MediaHandler is attached to a AV stream. */ bool isAttached(const CallMediaHandlerPtr& mediaHandler); // Components that a plugin can register through registerMediaHandler service. // These objects can then be activated with toggleCallMediaHandler. std::list<CallMediaHandlerPtr> callMediaHandlers_; // When there is a SIPCall, AVSubjects are created there. // Here we store their references in order to make them interact with MediaHandlers. // For easy access they are mapped with the call they belong to. std::map<std::string, std::list<std::pair<const StreamData, AVSubjectSPtr>>> callAVsubjects_; // Component that stores MediaHandlers' status for each existing call. // A map of callIds and MediaHandler-status pairs. std::map<std::string, std::map<uintptr_t, bool>> mediaHandlerToggled_; }; } // namespace jami
6,382
C++
.h
152
36.032895
97
0.699452
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
752,051
chathandler.h
savoirfairelinux_jami-daemon/src/plugin/chathandler.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 "observer.h" #include "streamdata.h" #include <string> #include <map> namespace jami { using pluginMessagePtr = std::shared_ptr<JamiMessage>; using chatSubjectPtr = std::shared_ptr<PublishObservable<pluginMessagePtr>>; /** * @brief This abstract class is an API we need to implement from plugin side. * In other words, a plugin functionality that plays with messages, must start * from the implementation of this class. */ class ChatHandler { public: virtual ~ChatHandler() {} /** * @brief Should attach a chat subject (Observable) and the plugin data process (Observer). * @param subjectConnection accountId, peerId pair * @param subject chat Subject pointer */ virtual void notifyChatSubject(std::pair<std::string, std::string>& subjectConnection, chatSubjectPtr subject) = 0; /** * @brief Returns a map with handler's name, iconPath, and pluginId. */ virtual std::map<std::string, std::string> getChatHandlerDetails() = 0; /** * @brief Should detach a chat subject (Observable) and the plugin data process (Observer). * @param subject chat subject pointer */ virtual void detach(chatSubjectPtr subject) = 0; /** * @brief If a preference can be changed without the need to reload the plugin, it * should be done through this function. * @param key * @param value */ virtual void setPreferenceAttribute(const std::string& key, const std::string& value) = 0; /** * @brief If a preference can be changed without the need to reload the plugin, this function * should return True. * @param key * @return True if preference can be changed through setPreferenceAttribute method. */ virtual bool preferenceMapHasKey(const std::string& key) = 0; /** * @brief Returns the dataPath of the plugin that created this ChatHandler. */ std::string id() const { return id_; } /** * @brief Should be called by the ChatHandler creator to set the plugins id_ variable. */ virtual void setId(const std::string& id) final { id_ = id; } private: // Is the dataPath of the plugin that created this ChatHandler. std::string id_; }; } // namespace jami
3,009
C++
.h
77
34.74026
97
0.702397
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
752,052
jamipluginmanager.h
savoirfairelinux_jami-daemon/src/plugin/jamipluginmanager.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 "noncopyable.h" #include "plugin/webviewservicesmanager.h" #include "pluginmanager.h" #include "pluginpreferencesutils.h" #include "callservicesmanager.h" #include "chatservicesmanager.h" #include "preferenceservicesmanager.h" #include <opendht/crypto.h> #include <vector> #include <map> #include <list> #include <algorithm> namespace jami { using PreferencesMap = std::map<std::string, std::map<std::string, std::string>>; /** * @class JamiPluginManager * @brief This class provides an interface to functions exposed to the * Plugin System interface for lrc and clients. */ class JamiPluginManager { public: JamiPluginManager(); /** * @brief get the plugin's author * @param rootPath * @param pluginId * @return string */ std::string getPluginAuthor(const std::string& rootPath, const std::string& pluginId); /** * @brief Parses a manifest file and return its content * along with other internally added values. * @param rootPath installation path * @param reset If true, overrides previous details values * Reset is only used in the UT for now, but it can be useful * if we want to reset plugins language without restarting the application * @return Map where the keyset is {"id", "name", "description", "version", "iconPath", "backgroundPath","soPath"} */ std::map<std::string, std::string> getPluginDetails(const std::string& rootPath, bool reset = false); /** * @brief Returns a vector with installed plugins */ std::vector<std::string> getInstalledPlugins(); /** * @brief Check the validity of a plugin certificate * @param cert * @return true if valid */ bool checkPluginCertificateValidity(dht::crypto::Certificate* cert); /** * @brief check if the if the public key of the certificate is the same as the public key in the new plugin * @param oldJplPath, newJplPath * return true if valid */ bool checkPluginCertificatePublicKey(const std::string& oldJplPath, const std::string& newJplPath); /** * @brief check if all file are present in the signature file * @param jplPath * return true if valid */ bool checkPluginSignatureFile(const std::string& jplPath); /** * @brief Check the validity of a plugin signature * @param jplPath * @param cert * @return true if valid */ bool checkPluginSignatureValidity(const std::string& jplPath, dht::crypto::Certificate* cert); /** * @brief Checks if the plugin signature mechanism is valid by signature of files and each files is signed. * @param jplPath * @param * @return true if the plugin signature is valid * */ bool checkPluginSignature(const std::string& jplPath, dht::crypto::Certificate* cert); /** * @brief Checks if the certificate mechanism is valid by checking certificate of the plugin * @param jplPath * @param force * @return return certificate if valid */ std::unique_ptr<dht::crypto::Certificate> checkPluginCertificate(const std::string& jplPath, bool force); /** * @brief Checks if the plugin has a valid manifest, installs the plugin if not * previously installed or if installing a newer version of it. * @param jplPath * @param force If true, allows installing an older plugin version. * @return 0 if success * 100 if already installed with similar version * 200 if already installed with newer version * libarchive (mizip in apple platforms) error codes otherwise */ int installPlugin(const std::string& jplPath, bool force); /** * @brief Checks if the plugin has a valid manifest and if the plugin is loaded, * tries to unload it and then removes plugin folder. * @param rootPath * @return 0 if success */ int uninstallPlugin(const std::string& rootPath); /** * @brief Returns True if success * @param rootPath of the plugin folder */ bool loadPlugin(const std::string& rootPath); /** * @brief Returns True if success */ bool loadPlugins(); /** * @brief Returns True if success * @param rootPath of the plugin folder */ bool unloadPlugin(const std::string& rootPath); /** * @brief Returns vector with rootpaths of the loaded plugins */ std::vector<std::string> getLoadedPlugins() const; /** * @brief Returns contents of plugin's preferences.json file * @param rootPath * @param accountId */ std::vector<std::map<std::string, std::string>> getPluginPreferences( const std::string& rootPath, const std::string& accountId); /** * @brief Returns a Map with preferences keys and values. * @param rootPath * @param accountId */ std::map<std::string, std::string> getPluginPreferencesValuesMap(const std::string& rootPath, const std::string& accountId); /** * @brief Returns a Map of platform system. */ std::map<std::string, std::string> getPlatformInfo(); /** * @brief Modifies a preference value by saving it to a preferences.msgpack. * Plugin is reloaded only if the preference cannot take effect immediately. * In other words, if we have to reload plugin so that preference may take effect. * @param rootPath * @param accountId * @param key * @param value * @return True if success */ bool setPluginPreference(const std::filesystem::path& rootPath, const std::string& accountId, const std::string& key, const std::string& value); /** * @brief Reset plugin's preferences values to their defaultValues * @param rootPath * @param accountId * @return True if success. */ bool resetPluginPreferencesValuesMap(const std::string& rootPath, const std::string& accountId); CallServicesManager& getCallServicesManager() { return callsm_; } ChatServicesManager& getChatServicesManager() { return chatsm_; } WebViewServicesManager& getWebViewServicesManager() { return webviewsm_; } PreferenceServicesManager& getPreferenceServicesManager() { return preferencesm_; } #ifdef LIBJAMI_TESTABLE void addPluginAuthority(const dht::crypto::Certificate& cert); #endif private: NON_COPYABLE(JamiPluginManager); /** * @brief Register services that can be called from plugin implementation side. */ void registerServices(); // PluginManager instance PluginManager pm_; dht::crypto::TrustList trust_; // Map between plugins installation path and manifest infos. std::map<std::string, std::map<std::string, std::string>> pluginDetailsMap_; // Services instances CallServicesManager callsm_; ChatServicesManager chatsm_; WebViewServicesManager webviewsm_; PreferenceServicesManager preferencesm_; }; } // namespace jami
7,829
C++
.h
201
33.40796
118
0.687788
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
752,053
streamdata.h
savoirfairelinux_jami-daemon/src/plugin/streamdata.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 <string> #include <map> enum class StreamType { audio, video }; /** * @struct StreamData * @brief Contains information about an AV subject. * It's used by CallServicesManager. */ struct StreamData { /** * @param callId * @param isReceived False if local audio/video streams * @param mediaType * @param conversationId * @param accountId */ StreamData(const std::string& callId, bool isReceived, const StreamType& mediaType, const std::string& conversationId, const std::string& accountId) : id {std::move(callId)} , direction {isReceived} , type {mediaType} , source {std::move(accountId)} , conversation {std::move(conversationId)} {} // callId const std::string id; // False if local audio/video. const bool direction; // StreamType -> audio or video. const StreamType type; // accountId const std::string source; // conversationId const std::string conversation; }; /** * @struct JamiMessage * @brief Contains information about an exchanged message. * It's used by ChatServicesManager. */ struct JamiMessage { /** * @param accId AccountId * @param pId peerId * @param isReceived True if received message, False if sent * @param dataMap Message contents * @param pPlugin True if message is created/modified by plugin code */ JamiMessage(const std::string& accId, const std::string& pId, bool isReceived, const std::map<std::string, std::string>& dataMap, bool pPlugin) : accountId {accId} , peerId {pId} , direction {isReceived} , data {dataMap} , fromPlugin {pPlugin} {} std::string accountId; std::string peerId; // True if it's a received message. const bool direction; std::map<std::string, std::string> data; // True if message is originated from Plugin code. bool fromPlugin; bool isSwarm {false}; bool fromHistory {false}; };
2,848
C++
.h
91
26.010989
73
0.661583
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
752,054
webviewhandler.h
savoirfairelinux_jami-daemon/src/plugin/webviewhandler.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 <map> #include <string> namespace jami { /** * @brief This is an abstract class (API) that needs to be implemented by a plugin. * Any plugin that wants to open a WebView needs to implement this class. */ class WebViewHandler { public: virtual ~WebViewHandler() {} /** * @brief Returns the dataPath of the plugin that created this WebViewHandler. */ std::string id() const { return id_; } /** * @brief Should be called by the WebViewHandler creator to set the plugin's id_ variable. */ virtual void setId(const std::string& id) final { id_ = id; } // these functions are called by the client and must be implemented by the plugin /** * @brief Called by the daemon whenever the client webview sends a message to the plugin */ virtual void pluginWebViewMessage(const std::string& webViewId, const std::string& messageId, const std::string& payload) = 0; /** * @brief Called by the daemon whenever the client attaches a new webview * @returns Relative path to an HTML file inside of the plugin's datapath */ virtual std::string pluginWebViewAttach(const std::string& accountId, const std::string& webViewId, const std::string& action) = 0; /** * @brief Called by the daemon whenever the client detaches a webview */ virtual void pluginWebViewDetach(const std::string& webViewId) = 0; private: // the dataPath of the plugin that created this WebViewHandler std::string id_; }; } // namespace jami
2,435
C++
.h
61
33.688525
94
0.666244
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
752,055
pluginmanager.h
savoirfairelinux_jami-daemon/src/plugin/pluginmanager.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 "noncopyable.h" #include "jamiplugin.h" #include "pluginloader.h" #include <functional> #include <map> #include <mutex> #include <vector> #include <list> #include <inttypes.h> namespace jami { /** * @class PluginManager * @brief This class manages plugin (un)loading. Those process include: * (1) plugin libraries (un)loading; * (2) call plugin initial function; * (3) handlers registration and destruction, and; * (4) services registration. */ class PluginManager { public: PluginManager(); ~PluginManager(); private: using ObjectDeleter = std::function<void(void*)>; // Function that may be called from plugin implementation using ServiceFunction = std::function<int32_t(const DLPlugin*, void*)>; // A Component is either a MediaHandler or a ChatHandler. // A ComponentFunction is a function that may start or end a component life. using ComponentFunction = std::function<int32_t(void*, std::mutex&)>; // A list of component type (MediaHandler or ChatHandler), and component pointer pairs using ComponentPtrList = std::list<std::pair<std::string, void*>>; struct ObjectFactory { JAMI_PluginObjectFactory data; ObjectDeleter deleter; }; /** * @struct ComponentLifeCycleManager * @brief Component functions for registration and destruction. */ struct ComponentLifeCycleManager { // Register component to servicesmanager ComponentFunction takeComponentOwnership; // Destroys component in servicesmanager ComponentFunction destroyComponent; }; // Map between plugin's library path and loader pointer using PluginMap = std::map<std::string, std::pair<std::shared_ptr<Plugin>, bool>>; // Map between plugins' library path and their components list using PluginComponentsMap = std::map<std::string, ComponentPtrList>; // Map with plugins' destruction functions using ExitFuncMap = std::map<std::string, JAMI_PluginExitFunc>; using ObjectFactoryVec = std::vector<ObjectFactory>; using ObjectFactoryMap = std::map<std::string, ObjectFactory>; public: /** * @brief Load a dynamic plugin by filename. * @param path fully qualified pathname on a loadable plugin binary * @return True if success */ bool load(const std::string& path); /** * @brief Unloads the plugin * @param path * @return True if success */ bool unload(const std::string& path); /** * @brief Returns vector with loaded plugins' libraries paths */ std::vector<std::string> getLoadedPlugins() const; /** * @brief Returns True if plugin is loaded */ bool checkLoadedPlugin(const std::string& rootPath) const; /** * @brief Register a new service in the Plugin System. * @param name The service name * @param func The function that may be called by Ring_PluginAPI.invokeService * @return True if success */ bool registerService(const std::string& name, ServiceFunction&& func); /** * @brief Unregister a service from the Plugin System. * @param name The service name */ void unRegisterService(const std::string& name); /** * @brief Function called from plugin implementation register a new object factory. * * Note: type can be the string "*" meaning that the factory * will be called if no exact match factories are found for a given type. * @param type unique identifier of the object * @param params object factory details * @return True if success */ bool registerObjectFactory(const char* type, const JAMI_PluginObjectFactory& factory); /** * @brief Registers a component manager that will have two functions, one to take * ownership of the component and the other one to destroy it * @param name name of the component manager * @param takeOwnership function that takes ownership on created objet in memory * @param destroyComponent destroy the component * @return True if success */ bool registerComponentManager(const std::string& name, ComponentFunction&& takeOwnership, ComponentFunction&& destroyComponent); private: NON_COPYABLE(PluginManager); /** * @brief Untoggle and destroys all plugin's handlers from handlerservices * @param path */ void destroyPluginComponents(const std::string& path); /** * @brief Returns True if success * @param path plugin path used as an id in the plugin map */ bool callPluginInitFunction(const std::string& path); /** * @brief Returns True if success * @param initFunc plugin init function */ bool registerPlugin(std::unique_ptr<Plugin>& plugin); /** * @brief Creates a new plugin's exported object. * @param type unique identifier of the object to create. * @return Unique pointer on created object. */ std::unique_ptr<void, ObjectDeleter> createObject(const std::string& type); /** * WARNING: exposed to plugins through JAMI_PluginAPI * @brief Implements JAMI_PluginAPI.registerObjectFactory(). * Must be C accessible. * @param api * @param type * @param data */ static int32_t registerObjectFactory_(const JAMI_PluginAPI* api, const char* type, void* data); /** WARNING: exposed to plugins through JAMI_PluginAPI * @brief Function called from plugin implementation to perform a service. * @param name The service name */ int32_t invokeService(const DLPlugin* plugin, const std::string& name, void* data); /** * WARNING: exposed to plugins through JAMI_PluginAPI * @brief Function called from plugin implementation to manage a component. * @param name The component type */ int32_t manageComponent(const DLPlugin* plugin, const std::string& name, void* data); std::mutex mutex_ {}; JAMI_PluginAPI pluginApi_ = {{JAMI_PLUGIN_ABI_VERSION, JAMI_PLUGIN_API_VERSION}, nullptr, // set by PluginManager constructor registerObjectFactory_, nullptr, nullptr}; // Keeps a map between plugin library path and a Plugin instance // for dynamically loaded plugins. PluginMap dynPluginMap_ {}; // Should keep reference to plugins' destruction functions read during library loading. ExitFuncMap exitFunc_ {}; ObjectFactoryMap exactMatchMap_ {}; ObjectFactoryVec wildCardVec_ {}; // Keeps a map between services names and service functions. std::map<std::string, ServiceFunction> services_ {}; // Keeps a ComponentsLifeCycleManager for each available Handler API. std::map<std::string, ComponentLifeCycleManager> componentsLifeCycleManagers_ {}; // Keeps a map between plugins' library path and their components list. PluginComponentsMap pluginComponentsMap_ {}; std::mutex mtx_; }; } // namespace jami
7,831
C++
.h
192
34.989583
99
0.694251
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
752,056
chatservicesmanager.h
savoirfairelinux_jami-daemon/src/plugin/chatservicesmanager.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 "noncopyable.h" #include "chathandler.h" #include "pluginpreferencesutils.h" namespace jami { class PluginManager; using ChatHandlerPtr = std::unique_ptr<ChatHandler>; /** * @brief This class provides the interface between loaded ChatHandlers * and conversation messages. Besides it: * (1) stores pointers to all loaded ChatHandlers; * (2) stores pointers to availables chat subjects, and; * (3) lists ChatHandler state with respect to each accountId, peerId pair. In other words, * for a given accountId, peerId pair, we store if a ChatHandler is active or not. */ class ChatServicesManager { public: /** * @brief Constructor registers ChatHandler API services to the PluginManager * instance. These services will store ChatHandler pointers, clean them * from the Plugin System once a plugin is loaded or unloaded, or yet allows * the plugins to send a message to a conversation. * @param pluginManager */ ChatServicesManager(PluginManager& pluginManager); NON_COPYABLE(ChatServicesManager); bool hasHandlers() const; /** * @brief List all ChatHandlers available. * @return Vector of stored ChatHandlers pointers. */ std::vector<std::string> getChatHandlers() const; /** * @brief Publishes every message sent or received in a conversation that has (or should have) * an active ChatHandler. * @param message */ void publishMessage(pluginMessagePtr message); /** * @brief If an account is unregistered or a contact is erased, we clear all chat subjects * related to that accountId or to the accountId, peerId pair. * @param accountId * @param peerId */ void cleanChatSubjects(const std::string& accountId, const std::string& peerId = ""); /** * @brief Activates or deactivate a given ChatHandler to a given accountId, peerId pair. * @param ChatHandlerId * @param accountId * @param peerId * @param toggle Notify with new subjects if true, detach if false. */ void toggleChatHandler(const std::string& chatHandlerId, const std::string& accountId, const std::string& peerId, const bool toggle); /** * @brief Returns a list of active ChatHandlers for a given accountId, peerId pair. * @param accountId * @param peerId * @return Vector with active ChatHandler ids for a given accountId, peerId pair. */ std::vector<std::string> getChatHandlerStatus(const std::string& accountId, const std::string& peerId); /** * @brief Gets details from ChatHandler implementation. * @param chatHandlerIdStr * @return Details map from the ChatHandler implementation */ std::map<std::string, std::string> getChatHandlerDetails(const std::string& chatHandlerIdStr); /** * @brief Sets a preference that may be changed while ChatHandler is active. * @param key * @param value * @param rootPath * @return False if preference was changed. */ bool setPreference(const std::string& key, const std::string& value, const std::string& rootPath); private: /** * @brief Exposes ChatHandlers' life cycle managers services to the main API. * @param pluginManager */ void registerComponentsLifeCycleManagers(PluginManager& pluginManager); /** * @brief Exposes ChatHandlers services that aren't related to handlers' life cycle * to the main API. * @param pluginManager */ void registerChatService(PluginManager& pluginManager); void toggleChatHandler(const uintptr_t chatHandlerId, const std::string& accountId, const std::string& peerId, const bool toggle); // Components that a plugin can register through registerChatHandler service. // These objects can then be activated with toggleChatHandler. std::list<ChatHandlerPtr> chatHandlers_; // Component that stores active ChatHandlers for each existing accountId, peerId pair. std::map<std::pair<std::string, std::string>, std::set<uintptr_t>> chatHandlerToggled_; // When there is a new message, chat subjects are created. // Here we store a reference to them in order to make them interact with // ChatHandlers. // For easy access they are mapped accordingly to the accountId, peerId pair to // which they belong. std::map<std::pair<std::string, std::string>, chatSubjectPtr> chatSubjects_; // Maps a ChatHandler name and the address of this ChatHandler. std::map<std::string, uintptr_t> handlersNameMap_ {}; // Component that stores persistent ChatHandlers' status for each existing // accountId, peerId pair. // A map of accountId, peerId pairs and ChatHandler-status pairs. ChatHandlerList allowDenyList_ {}; }; } // namespace jami
5,766
C++
.h
132
37.439394
98
0.693514
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
752,057
account_config_utils.h
savoirfairelinux_jami-daemon/src/config/account_config_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 "yamlparser.h" template<typename T> inline void serializeValue(YAML::Emitter& out, const char* key, const T& value, const T& def) { if (value != def) out << YAML::Key << key << YAML::Value << value; } #define SERIALIZE_CONFIG(key, name) serializeValue(out, key, name, DEFAULT_CONFIG.name) #define SERIALIZE_PATH(key, name) serializeValue(out, key, fileutils::getCleanPath(path.string(), name), DEFAULT_CONFIG.name)
1,168
C++
.h
25
44.56
125
0.738826
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
752,058
serializable.h
savoirfairelinux_jami-daemon/src/config/serializable.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 YAML { class Emitter; class Node; } // namespace YAML namespace jami { class Serializable { public: virtual ~Serializable() {}; virtual void serialize(YAML::Emitter& out) const = 0; virtual void unserialize(const YAML::Node& node) = 0; }; } // namespace jami
1,015
C++
.h
30
31.8
73
0.743119
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
752,059
yamlparser.h
savoirfairelinux_jami-daemon/src/config/yamlparser.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 "logger.h" #include <yaml-cpp/yaml.h> #include <filesystem> namespace jami { namespace yaml_utils { // set T to the value stored at key, or leaves T unchanged // if no value is stored. template<typename T> void parseValue(const YAML::Node& node, const char* key, T& value) { value = node[key].as<T>(); } template<typename T> bool parseValueOptional(const YAML::Node& node, const char* key, T& value) { try { parseValue(node, key, value); return true; } catch (const std::exception& e) { // JAMI_DBG("Unable to read yaml field: %s", key); } return false; } void parsePath(const YAML::Node& node, const char* key, std::string& path, const std::filesystem::path& base); void parsePathOptional(const YAML::Node& node, const char* key, std::string& path, const std::filesystem::path& base); std::vector<std::map<std::string, std::string>> parseVectorMap( const YAML::Node& node, const std::initializer_list<std::string>& keys); std::set<std::string> parseVector(const YAML::Node& node); } // namespace yaml_utils } // namespace jami
1,823
C++
.h
49
34.755102
118
0.721971
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
752,060
pres_sub_server.h
savoirfairelinux_jami-daemon/src/sip/pres_sub_server.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/>. */ #ifndef SERVERPRESENCESUB_H #define SERVERPRESENCESUB_H #include <pj/string.h> #include <pjsip/sip_types.h> #include <pjsip-simple/evsub.h> #include <pjsip-simple/presence.h> #include <pjsip/sip_module.h> #include "noncopyable.h" namespace jami { extern pj_bool_t pres_on_rx_subscribe_request(pjsip_rx_data* rdata); class SIPPresence; class PresSubServer { public: PresSubServer(SIPPresence* pres, pjsip_evsub* evsub, const char* remote, pjsip_dialog* d); ~PresSubServer(); /* * Access to the evsub expire variable. * It was received in the SUBSCRIBE request. */ void setExpires(int ms); int getExpires() const; /* * Match method * s is the URI (remote) */ bool matches(const char* s) const; /* * Allow the subscriber for being notified. */ void approve(bool flag); /* * Notify subscriber with the pres_status_date of the account */ void notify(); static pjsip_module mod_presence_server; private: static pj_bool_t pres_on_rx_subscribe_request(pjsip_rx_data* rdata); static void pres_evsub_on_srv_state(pjsip_evsub* sub, pjsip_event* event); NON_COPYABLE(PresSubServer); /* TODO: add '< >' to URI for consistency */ const char* remote_; /**< Remote URI. */ SIPPresence* pres_; pjsip_evsub* sub_; pjsip_dialog* dlg_; int expires_; bool approved_; }; } // namespace jami #endif /* SERVERPRESENCESUB_H */
2,184
C++
.h
66
29.590909
94
0.702754
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
752,061
sdp.h
savoirfairelinux_jami-daemon/src/sip/sdp.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 "noncopyable.h" #include "sdes_negotiator.h" #include "media/media_codec.h" #include "media/media_attribute.h" #include "connectivity/sip_utils.h" #include <dhtnet/ip_utils.h> #include <dhtnet/ice_transport.h> #include <pjmedia/sdp.h> #include <pjmedia/sdp_neg.h> #include <pjsip/sip_transport.h> #include <pjlib.h> #include <pjsip_ua.h> #include <pjmedia/errno.h> #include <pj/pool.h> #include <pj/assert.h> #include <map> #include <vector> #include <string> #include <stdexcept> namespace jami { namespace test { class SDPTest; } class AudioCodec; class SdpException : public std::runtime_error { public: SdpException(const std::string& str = "") : std::runtime_error("SDP: SdpException occurred: " + str) {} }; enum class SdpDirection { OFFER, ANSWER, NONE }; class Sdp { public: /* * Class Constructor. * * @param memory pool */ Sdp(const std::string& id); ~Sdp(); /** * Set the local media capabilities. * @param List of codec in preference order */ void setLocalMediaCapabilities( MediaType type, const std::vector<std::shared_ptr<SystemCodecInfo>>& selectedCodecs); /** * Read accessor. Get the local passive sdp session information before negotiation * * @return The structure that describes a SDP session */ pjmedia_sdp_session* getLocalSdpSession() { return localSession_; } const pjmedia_sdp_session* getActiveLocalSdpSession() const { return activeLocalSession_; } /** * Read accessor. Get the remote passive sdp session information before negotiation * * @return The structure that describe the SDP session */ pjmedia_sdp_session* getRemoteSdpSession() { return remoteSession_; } const pjmedia_sdp_session* getActiveRemoteSdpSession() const { return activeRemoteSession_; } /** * Set the negotiated sdp offer from the sip payload. * * @param sdp the negotiated offer */ void setActiveLocalSdpSession(const pjmedia_sdp_session* sdp); /** * Retrieve the negotiated sdp offer from the sip payload. * * @param sdp the negotiated offer */ void setActiveRemoteSdpSession(const pjmedia_sdp_session* sdp); /* * On building an invite outside a dialog, build the local offer and create the * SDP negotiator instance with it. * @returns true if offer was created, false otherwise */ bool createOffer(const std::vector<MediaAttribute>& mediaList); void setReceivedOffer(const pjmedia_sdp_session* remote); /** * Build a new SDP answer using mediaList. * * @param mediaList The list of media attributes to build the answer */ bool processIncomingOffer(const std::vector<MediaAttribute>& mediaList); /** * Start the sdp negotiation. */ bool startNegotiation(); /** * Remove all media in the session media vector. */ void cleanSessionMedia(); /* * Write accessor. Set the local IP address that will be used in the sdp session */ void setPublishedIP(const std::string& addr, pj_uint16_t addr_type = pj_AF_UNSPEC()); void setPublishedIP(const dhtnet::IpAddr& addr); /* * Read accessor. Get the local IP address */ dhtnet::IpAddr getPublishedIPAddr() const { return std::string_view(publishedIpAddr_); } std::string_view getPublishedIP() const { return publishedIpAddr_; } void setLocalPublishedAudioPorts(uint16_t audio_port, uint16_t control_port) { localAudioRtpPort_ = audio_port; localAudioRtcpPort_ = control_port; } void setLocalPublishedVideoPorts(uint16_t video_port, uint16_t control_port) { localVideoRtpPort_ = video_port; localVideoRtcpPort_ = control_port; } uint16_t getLocalVideoPort() const { return localVideoRtpPort_; } uint16_t getLocalVideoControlPort() const { return localVideoRtcpPort_; } uint16_t getLocalAudioPort() const { return localAudioRtpPort_; } uint16_t getLocalAudioControlPort() const { return localAudioRtcpPort_; } std::vector<MediaDescription> getActiveMediaDescription(bool remote) const; std::vector<MediaDescription> getMediaDescriptions(const pjmedia_sdp_session* session, bool remote) const; static std::vector<MediaAttribute> getMediaAttributeListFromSdp( const pjmedia_sdp_session* sdpSession, bool ignoreDisabled = false); using MediaSlot = std::pair<MediaDescription, MediaDescription>; std::vector<MediaSlot> getMediaSlots() const; unsigned int getTelephoneEventType() const { return telephoneEventPayload_; } void addIceAttributes(const dhtnet::IceTransport::Attribute&& ice_attrs); dhtnet::IceTransport::Attribute getIceAttributes() const; static dhtnet::IceTransport::Attribute getIceAttributes(const pjmedia_sdp_session* session); void addIceCandidates(unsigned media_index, const std::vector<std::string>& cands); std::vector<std::string> getIceCandidates(unsigned media_index) const; void clearIce(); SdpDirection getSdpDirection() const { return sdpDirection_; }; static const char* getSdpDirectionStr(SdpDirection direction); /// \brief Log the given session /// \note crypto lines with are removed for security static void printSession(const pjmedia_sdp_session* session, const char* header, SdpDirection direction); private: friend class test::SDPTest; NON_COPYABLE(Sdp); void getProfileLevelID(const pjmedia_sdp_session* session, std::string& dest, int payload) const; /** * Returns the printed original SDP filtered with only the specified media index and codec * remaining. */ static std::string getFilteredSdp(const pjmedia_sdp_session* session, unsigned media_keep, unsigned pt_keep); static void clearIce(pjmedia_sdp_session* session); /* * Build the sdp media section * Add rtpmap field if necessary */ pjmedia_sdp_media* addMediaDescription(const MediaAttribute& mediaAttr); // Determine media direction char const* mediaDirection(const MediaAttribute& mediaAttr); // Get media direction static MediaDirection getMediaDirection(pjmedia_sdp_media* media); // Get the transport type static MediaTransport getMediaTransport(pjmedia_sdp_media* media); // Get the crypto materials static std::vector<std::string> getCrypto(pjmedia_sdp_media* media); pjmedia_sdp_attr* generateSdesAttribute(); void setTelephoneEventRtpmap(pjmedia_sdp_media* med); /* * Create a new SDP */ void createLocalSession(SdpDirection direction); /* * Validate SDP */ int validateSession() const; /* * Adds a sdes attribute to the given media section. * * @param media The media to add the srtp attribute to * @throw SdpException */ void addSdesAttribute(const std::vector<std::string>& crypto); void addRTCPAttribute(pjmedia_sdp_media* med, uint16_t port); std::shared_ptr<SystemCodecInfo> findCodecByPayload(const unsigned payloadType); std::shared_ptr<SystemCodecInfo> findCodecBySpec(std::string_view codecName, const unsigned clockrate = 0) const; // Data members std::unique_ptr<pj_pool_t, std::function<void(pj_pool_t*)>> memPool_; pjmedia_sdp_neg* negotiator_ {nullptr}; pjmedia_sdp_session* localSession_ {nullptr}; pjmedia_sdp_session* remoteSession_ {nullptr}; /** * The negotiated SDP remote session * Explanation: each endpoint's offer is negotiated, and a new sdp offer results from this * negotiation, with the compatible media from each part */ const pjmedia_sdp_session* activeLocalSession_ {nullptr}; /** * The negotiated SDP remote session * Explanation: each endpoint's offer is negotiated, and a new sdp offer results from this * negotiation, with the compatible media from each part */ const pjmedia_sdp_session* activeRemoteSession_ {nullptr}; /** * Codec Map used for offer */ std::vector<std::shared_ptr<SystemCodecInfo>> audio_codec_list_; std::vector<std::shared_ptr<SystemCodecInfo>> video_codec_list_; std::string publishedIpAddr_; pj_uint16_t publishedIpAddrType_; uint16_t localAudioRtpPort_ {0}; uint16_t localAudioRtcpPort_ {0}; uint16_t localVideoRtpPort_ {0}; uint16_t localVideoRtcpPort_ {0}; unsigned int telephoneEventPayload_; // The call Id of the SDP owner std::string sessionName_ {}; // Offer/Answer flag. SdpDirection sdpDirection_ {SdpDirection::NONE}; }; } // namespace jami
9,622
C++
.h
238
34.638655
101
0.701847
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
752,062
sipaccount.h
savoirfairelinux_jami-daemon/src/sip/sipaccount.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 #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "sip/sipaccountbase.h" #include "sip/siptransport.h" #include "noncopyable.h" #include "ring_types.h" // enable_if_base_of #include "sipaccount_config.h" #include <pjsip/sip_transport_tls.h> #include <pjsip/sip_types.h> #include <pjsip-ua/sip_regc.h> #include <vector> #include <map> namespace jami { typedef std::vector<pj_ssl_cipher> CipherArray; class SIPPresence; class SIPCall; /** * @file sipaccount.h * @brief A SIP Account specify SIP specific functions and object = SIPCall/SIPVoIPLink) */ class SIPAccount : public SIPAccountBase { public: constexpr static auto ACCOUNT_TYPE = ACCOUNT_TYPE_SIP; std::shared_ptr<SIPAccount> shared() { return std::static_pointer_cast<SIPAccount>(shared_from_this()); } std::shared_ptr<SIPAccount const> shared() const { return std::static_pointer_cast<SIPAccount const>(shared_from_this()); } std::weak_ptr<SIPAccount> weak() { return std::static_pointer_cast<SIPAccount>(shared_from_this()); } std::weak_ptr<SIPAccount const> weak() const { return std::static_pointer_cast<SIPAccount const>(shared_from_this()); } /** * Constructor * @param accountID The account identifier */ SIPAccount(const std::string& accountID, bool presenceEnabled); ~SIPAccount() noexcept; const SipAccountConfig& config() const { return *static_cast<const SipAccountConfig*>(&Account::config()); } std::unique_ptr<AccountConfig> buildConfig() const override { return std::make_unique<SipAccountConfig>(getAccountID()); } inline void editConfig(std::function<void(SipAccountConfig& conf)>&& edit) { Account::editConfig( [&](AccountConfig& conf) { edit(*static_cast<SipAccountConfig*>(&conf)); }); } std::string_view getAccountType() const override { return ACCOUNT_TYPE; } pjsip_host_port getHostPortFromSTUN(pj_pool_t* pool); void updateDialogViaSentBy(pjsip_dialog* dlg); void resetAutoRegistration(); /** * Update NAT address, Via and Contact header from the REGISTER response * @param param pjsip reg cbparam * @param pool * @return update status */ bool checkNATAddress(pjsip_regc_cbparam* param, pj_pool_t* pool); /** * Returns true if this is the IP2IP account */ bool isIP2IP() const override; /** * Retrieve volatile details such as recent registration errors * @return std::map< std::string, std::string > The account volatile details */ virtual std::map<std::string, std::string> getVolatileAccountDetails() const override; /** * Return the TLS settings, mainly used to return security information to * a client application */ std::map<std::string, std::string> getTlsSettings() const; /** * Actually useless, since config loading is done in init() */ void loadConfig() override; /** * Initialize the SIP voip link with the account parameters and send registration */ void doRegister() override; /** * Send unregistration. */ void doUnregister(std::function<void(bool)> cb = std::function<void(bool)>()) override; /** * Build and send SIP registration request */ void sendRegister(); /** * Build and send SIP unregistration request * @param destroy_transport If true, attempt to destroy the transport. */ void sendUnregister(); const pjsip_cred_info* getCredInfo() const { return cred_.data(); } /** * Get the number of credentials defined for * this account. * @param none * @return int The number of credentials set for this account. */ unsigned getCredentialCount() const { return config().credentials.size(); } bool hasCredentials() const { return not config().credentials.empty(); } std::vector<std::map<std::string, std::string>> getCredentials() const { return config().getCredentials(); } virtual void setRegistrationState(RegistrationState state, int code = 0, const std::string& detail_str = {}) override; /** * A client sendings a REGISTER request MAY suggest an expiration * interval that indicates how long the client would like the * registration to be valid. * * @return the expiration value. */ unsigned getRegistrationExpire() const { unsigned re = config().registrationExpire; return re ? re : PJSIP_REGC_EXPIRATION_NOT_SPECIFIED; } /** * Registration flag */ bool isRegistered() const { return bRegister_; } /** * Get the registration structure that is used * for PJSIP in the registration process. * Settings are loaded from configuration file. * @return pjsip_regc* A pointer to the registration structure */ pjsip_regc* getRegistrationInfo() { return regc_; } /** * Set the registration structure that is used * for PJSIP in the registration process; * @pram A pointer to the new registration structure * @return void */ void setRegistrationInfo(pjsip_regc* regc) { if (regc_) destroyRegistrationInfo(); regc_ = regc; } void destroyRegistrationInfo(); /** * Get the port on which the transport/listener should use, or is * actually using. * @return pj_uint16 The port used for that account */ uint16_t getLocalPort() const { return config().localPort; } void setLocalPort(uint16_t port) { editConfig([&](SipAccountConfig& config) { config.localPort = port; }); } /** * @return pjsip_tls_setting structure, filled from the configuration * file, that can be used directly by PJSIP to initialize * TLS transport. */ pjsip_tls_setting* getTlsSetting() { return &tlsSetting_; } /** * Get the local port for TLS listener. * @return pj_uint16 The port used for that account */ pj_uint16_t getTlsListenerPort() const { return config().tlsListenerPort; } pj_str_t getStunServerName() const { return stunServerName_; } static const std::vector<std::string>& getSupportedTlsCiphers(); static const std::vector<std::string>& getSupportedTlsProtocols(); /** * @return pj_uint8_t structure, filled from the configuration * file, that can be used directly by PJSIP to initialize * an alternate UDP transport. */ pj_uint16_t getStunPort() const override { return stunPort_; } /** * @return bool Tells if current transport for that * account is set to OTHER. */ bool isStunEnabled() const override { return config().stunEnabled; } /** * @return pj_str_t , filled from the configuration * file, that can be used directly by PJSIP to initialize * an alternate UDP transport. */ std::string getStunServer() const { return config().stunServer; } /** * @return pj_str_t "From" uri based on account information. * From RFC3261: "The To header field first and foremost specifies the desired * logical" recipient of the request, or the address-of-record of the * user or resource that is the target of this request. [...] As such, it is * very important that the From URI not contain IP addresses or the FQDN * of the host on which the UA is running, since these are not logical * names." */ std::string getFromUri() const override; /** * This method adds the correct scheme, hostname and append * the ;transport= parameter at the end of the uri, in accordance with RFC3261. * It is expected that "port" is present in the internal hostname_. * * @return pj_str_t "To" uri based on @param username * @param username A string formatted as : "username" */ std::string getToUri(const std::string& username) const override; /** * In the current version, "srv" uri is obtained in the preformatted * way: hostname:port. This method adds the correct scheme and append * the ;transport= parameter at the end of the uri, in accordance with RFC3261. * * @return pj_str_t "server" uri based on @param hostPort * @param hostPort A string formatted as : "hostname:port" */ std::string getServerUri() const; /** * Get the contact address * @return The current contact address */ dhtnet::IpAddr getContactAddress() const; /** * Get the contact header * @return The current contact header */ std::string getContactHeader() const; std::string getServiceRoute() const { return config().serviceRoute; } bool hasServiceRoute() const { return not config().serviceRoute.empty(); } virtual bool isTlsEnabled() const override { return config().tlsEnable; } virtual bool getSrtpFallback() const override { return config().srtpFallback; } void setReceivedParameter(const std::string& received) { receivedParameter_ = received; via_addr_.host = sip_utils::CONST_PJ_STR(receivedParameter_); } const std::string& getReceivedParameter() const { return receivedParameter_; } pjsip_host_port* getViaAddr() { return &via_addr_; } int getRPort() const { if (rPort_ == -1) return config().localPort; else return rPort_; } void setRPort(int rPort) { rPort_ = rPort; via_addr_.port = rPort; } bool isRegistrationRefreshEnabled() const { return config().registrationRefreshEnabled; } void setTransport(const std::shared_ptr<SipTransport>& = nullptr); virtual inline std::shared_ptr<SipTransport> getTransport() { return transport_; } inline pjsip_transport_type_e getTransportType() const { return transportType_; } /** * Shortcut for SipTransport::getTransportSelector(account.getTransport()). */ pjsip_tpselector getTransportSelector(); /* Returns true if the username and/or hostname match this account */ MatchRank matches(std::string_view username, std::string_view hostname) const override; /** * Presence management */ SIPPresence* getPresence() const; /** * Activate the module. * @param function Publish or subscribe to enable * @param enable Flag */ void enablePresence(const bool& enable); /** * Activate the publish/subscribe. * @param enable Flag */ void supportPresence(int function, bool enable); /** * Create outgoing SIPCall. * @param[in] toUrl the address to call * @param[in] mediaList list of medias * @return a shared pointer on the created call. */ std::shared_ptr<Call> newOutgoingCall(std::string_view toUrl, const std::vector<libjami::MediaMap>& mediaList) override; /** * Create incoming SIPCall. * @param[in] from The origin of the call * @param mediaList A list of media * @param sipTr: SIP Transport * @return A shared pointer on the created call. */ std::shared_ptr<SIPCall> newIncomingCall( const std::string& from, const std::vector<libjami::MediaMap>& mediaList, const std::shared_ptr<SipTransport>& sipTr = {}) override; void onRegister(pjsip_regc_cbparam* param); virtual void sendMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t id, bool retryOnTimeout = true, bool onlyConnected = false) override; void connectivityChanged() override; std::string getUserUri() const override; /** * Create the Ip address that the transport uses * @return IpAddr created */ dhtnet::IpAddr createBindingAddress(); void setActiveCodecs(const std::vector<unsigned>& list) override; bool isSrtpEnabled() const override { return config().srtpKeyExchange != KeyExchangeProtocol::NONE; } bool setPushNotificationToken(const std::string& pushDeviceToken = "") override; bool setPushNotificationConfig(const std::map<std::string, std::string>& data) override; /** * To be called by clients with relevant data when a push notification is received. */ void pushNotificationReceived(const std::string& from, const std::map<std::string, std::string>& data); private: void doRegister1_(); void doRegister2_(); // Initialize the address to be used in contact header. Might // be updated (as the contact header)after the registration. bool initContactAddress(); void updateContactHeader(); void setCredentials(const std::vector<SipAccountConfig::Credentials>& creds); void setUpTransmissionData(pjsip_tx_data* tdata, long transportKeyType); NON_COPYABLE(SIPAccount); std::shared_ptr<Call> newRegisteredAccountCall(const std::string& id, const std::string& toUrl); /** * Start a SIP Call * @param call The current call * @return true if all is correct */ bool SIPStartCall(std::shared_ptr<SIPCall>& call); void usePublishedAddressPortInVIA(); void useUPnPAddressPortInVIA(); bool fullMatch(std::string_view username, std::string_view hostname) const; bool userMatch(std::string_view username) const; bool hostnameMatch(std::string_view hostname) const; bool proxyMatch(std::string_view hostname) const; /** * Callback called by the transport layer when the registration * transport state changes. */ virtual void onTransportStateChanged(pjsip_transport_state state, const pjsip_transport_state_info* info); struct { pj_bool_t active {false}; /**< Flag of reregister status. */ pj_timer_entry timer {}; /**< Timer for reregistration. */ unsigned attempt_cnt {0}; /**< Attempt counter. */ } auto_rereg_ {}; /**< Reregister/reconnect data. */ std::uniform_int_distribution<int> delay10ZeroDist_ {-10000, 10000}; std::uniform_int_distribution<unsigned int> delay10PosDist_ {0, 10000}; void scheduleReregistration(); void autoReregTimerCb(); std::shared_ptr<SipTransport> transport_ {}; std::shared_ptr<TlsListener> tlsListener_ {}; /** * Transport type used for this sip account. Currently supported types: * PJSIP_TRANSPORT_UNSPECIFIED * PJSIP_TRANSPORT_UDP * PJSIP_TRANSPORT_TLS */ pjsip_transport_type_e transportType_ {PJSIP_TRANSPORT_UNSPECIFIED}; /** * Maps a string description of the SSL method * to the corresponding enum value in pjsip_ssl_method. * @param method The string representation * @return pjsip_ssl_method The corresponding value in the enum */ static pj_uint32_t tlsProtocolFromString(const std::string& method); /** * Initializes tls settings from configuration file. */ void initTlsConfiguration(); /** * PJSIP aborts if the string length of our cipher list is too * great, so this function forces our cipher list to fit this constraint. */ void trimCiphers(); /** * Initializes STUN config from the config file */ void initStunConfiguration(); /** * If username is not provided, as it happens for Direct ip calls, * fetch the Real Name field of the user that is currently * running this program. * @return std::string The login name under which the software is running. */ static std::string getLoginName(); /** * Maps require port via UPnP */ bool mapPortUPnP(); /** * Print contact header in certain format */ static std::string printContactHeader(const std::string& username, const std::string& displayName, const std::string& address, pj_uint16_t port, bool secure, const std::string& deviceKey = {}); /** * Resolved IP of hostname_ (for registration) */ dhtnet::IpAddr hostIp_; /** * The pjsip client registration information */ pjsip_regc* regc_ {nullptr}; /** * To check if the account is registered */ bool bRegister_; /** * Credential information stored for further registration. * Points to credentials_ members. */ std::vector<pjsip_cred_info> cred_; /** * The TLS settings, used only if tls is chosen as a sip transport. */ pjsip_tls_setting tlsSetting_; /** * Allocate a vector to be used by pjsip to store the supported ciphers on this system. */ CipherArray ciphers_; /** * The STUN server name (hostname) */ pj_str_t stunServerName_ {nullptr, 0}; /** * The STUN server port */ pj_uint16_t stunPort_ {PJ_STUN_PORT}; /** * Send Request Callback */ static void onComplete(void* token, pjsip_event* event); /** * Details about the registration state. * This is a protocol Code:Description pair. */ std::pair<int, std::string> registrationStateDetailed_; /** * Optional: "received" parameter from VIA header */ std::string receivedParameter_; /** * Optional: "rport" parameter from VIA header */ int rPort_ {-1}; /** * Optional: via_addr construct from received parameters */ pjsip_host_port via_addr_; // This is used at runtime . Mainly by SIPAccount::usePublishedAddressPortInVIA() std::string publishedIpStr_ {}; /** * Temporary storage for getUPnPIpAddress().toString() * Used only by useUPnPAddressPortInVIA(). */ std::string upnpIpAddr_; mutable std::mutex contactMutex_; // Contact header std::string contactHeader_; // Contact address (the address part of a SIP URI) dhtnet::IpAddr contactAddress_ {}; pjsip_transport* via_tp_ {nullptr}; /** * Presence data structure */ SIPPresence* presence_; /** * SIP port actually used, * this holds the actual port used for SIP, which may not be the port * selected in the configuration in the case that UPnP is used and the * configured port is already used by another client */ pj_uint16_t publishedPortUsed_ {sip_utils::DEFAULT_SIP_PORT}; }; } // namespace jami
19,548
C++
.h
515
31.440777
100
0.659336
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
752,063
sipaccountbase.h
savoirfairelinux_jami-daemon/src/sip/sipaccountbase.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 #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "account.h" #include "connectivity/sip_utils.h" #include "noncopyable.h" #include "im/message_engine.h" #include "sipaccountbase_config.h" #include <dhtnet/turn_cache.h> #include <dhtnet/ip_utils.h> #include <dhtnet/ice_options.h> #include <array> #include <deque> #include <map> #include <memory> #include <mutex> #include <vector> extern "C" { #include <pjsip/sip_types.h> #ifdef _WIN32 typedef uint16_t in_port_t; #else #include <netinet/in.h> // For in_port_t support #endif struct pjsip_dialog; struct pjsip_inv_session; struct pjmedia_sdp_session; } static constexpr const char MIME_TYPE_TEXT_PLAIN[] {"text/plain"}; namespace jami { class SipTransport; class Task; typedef std::vector<pj_ssl_cipher> CipherArray; class SIPVoIPLink; class SIPCall; /** * @file sipaccount.h * @brief A SIP Account specify SIP specific functions and object = SIPCall/SIPVoIPLink) */ enum class MatchRank { NONE, PARTIAL, FULL }; class SIPAccountBase : public Account { public: constexpr static unsigned MAX_PORT {65536}; constexpr static unsigned HALF_MAX_PORT {MAX_PORT / 2}; /** * Constructor * @param accountID The account identifier */ SIPAccountBase(const std::string& accountID); virtual ~SIPAccountBase() noexcept; const SipAccountBaseConfig& config() const { return *static_cast<const SipAccountBaseConfig*>(&Account::config()); } void loadConfig() override; /** * Create incoming SIPCall. * @param[in] from The origin of the call * @param mediaList A list of media * @param sipTr: SIP Transport * @return A shared pointer on the created call. */ virtual std::shared_ptr<SIPCall> newIncomingCall(const std::string& from, const std::vector<libjami::MediaMap>& mediaList, const std::shared_ptr<SipTransport>& sipTr = {}) = 0; virtual bool isStunEnabled() const { return false; } virtual pj_uint16_t getStunPort() const { return 0; }; virtual std::string getDtmfType() const { return config().dtmfType; } /** * Determine if TLS is enabled for this account. TLS provides a secured channel for * SIP signalization. It is independent of the media encryption (as provided by SRTP). */ virtual bool isTlsEnabled() const { return false; } /** * Create UAC attached dialog and invite session * @return true if success. false if failure and dlg and inv pointers * should not be considered as valid. */ bool 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); /** * Get the local interface name on which this account is bound. */ const std::string& getLocalInterface() const { return config().interface; } /** * Get the public IP address set by the user for this account. * If this setting is not provided, the local bound adddress * will be used. * @return std::string The public IPv4 or IPv6 address formatted in standard notation. */ std::string getPublishedAddress() const { return config().publishedIp; } virtual dhtnet::IpAddr getPublishedIpAddress(uint16_t family = PF_UNSPEC) const; void setPublishedAddress(const dhtnet::IpAddr& ip_addr); /** * Get a flag which determine the usage in sip headers of either the local * IP address and port (_localAddress and localPort_) or to an address set * manually (_publishedAddress and publishedPort_). */ bool getPublishedSameasLocal() const { return config().publishedSameasLocal; } virtual bool isSrtpEnabled() const = 0; virtual bool getSrtpFallback() const = 0; virtual std::string getToUri(const std::string& username) const = 0; /** * Socket port generators for media * Note: given ports are application wide, a port is unable to be given again * by any account instances until it's released by the static method * releasePort(). */ uint16_t generateAudioPort() const; #ifdef ENABLE_VIDEO uint16_t generateVideoPort() const; #endif static void releasePort(uint16_t port) noexcept; virtual dhtnet::IceTransportOptions getIceOptions() const noexcept; virtual void sendMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t id, bool retryOnTimeout = true, bool onlyConnected = false) = 0; virtual uint64_t sendTextMessage(const std::string& to, const std::string& deviceId, const std::map<std::string, std::string>& payloads, uint64_t refreshToken = 0, bool onlyConnected = false) override { if (onlyConnected) { auto token = std::uniform_int_distribution<uint64_t> {1, JAMI_ID_MAX_VAL}(rand); sendMessage(to, deviceId, payloads, token, false, true); return token; } return messageEngine_.sendMessage(to, deviceId, payloads, refreshToken); } im::MessageStatus getMessageStatus(uint64_t id) const override { return messageEngine_.getStatus(id); } virtual void onTextMessage(const std::string& id, const std::string& from, const std::string& deviceId, const std::map<std::string, std::string>& payloads); /* Returns true if the username and/or hostname match this account */ virtual MatchRank matches(std::string_view username, std::string_view hostname) const = 0; void connectivityChanged() override {}; virtual std::string getUserUri() const = 0; std::vector<libjami::Message> getLastMessages(const uint64_t& base_timestamp) override; // Build the list of medias to be included in the SDP (offer/answer) std::vector<MediaAttribute> createDefaultMediaList(bool addVideo, bool onHold = false); public: // overloaded methods virtual void flush() override; protected: /** * Retrieve volatile details such as recent registration errors * @return std::map< std::string, std::string > The account volatile details */ virtual std::map<std::string, std::string> getVolatileAccountDetails() const override; virtual void setRegistrationState(RegistrationState state, int code = 0, const std::string& detail_str = {}) override; im::MessageEngine messageEngine_; /** * Voice over IP Link contains a listener thread and calls */ SIPVoIPLink& link_; /** * Published IPv4/IPv6 addresses, used only if defined by the user in account * configuration * */ dhtnet::IpAddr publishedIp_[2] {}; pj_status_t transportStatus_ {PJSIP_SC_TRYING}; std::string transportError_ {}; static std::array<bool, HALF_MAX_PORT>& getPortsReservation() noexcept; static uint16_t acquirePort(uint16_t port); uint16_t getRandomEvenPort(const std::pair<uint16_t, uint16_t>& range) const; uint16_t acquireRandomEvenPort(const std::pair<uint16_t, uint16_t>& range) const; /** * The deamon can be launched without any client (or with a non ready client) * Like call and file transfer, a client should be able to retrieve current messages. * To avoid to explode the size in memory, this container should be limited. * We don't want to see monsters in memory. */ std::mutex mutexLastMessages_; static constexpr size_t MAX_WAITING_MESSAGES_SIZE = 1000; std::deque<libjami::Message> lastMessages_; std::shared_ptr<dhtnet::TurnCache> turnCache_; private: NON_COPYABLE(SIPAccountBase); }; } // namespace jami
9,157
C++
.h
215
34.772093
101
0.653837
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
752,064
sipaccountbase_config.h
savoirfairelinux_jami-daemon/src/sip/sipaccountbase_config.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 "account_config.h" namespace jami { constexpr static const char* const OVERRTP_STR = "overrtp"; constexpr static const char* const SIPINFO_STR = "sipinfo"; constexpr static unsigned MAX_PORT {65536}; constexpr static unsigned HALF_MAX_PORT {MAX_PORT / 2}; struct SipAccountBaseConfig: public AccountConfig { SipAccountBaseConfig(const std::string& type, const std::string& id, const std::filesystem::path& path) : AccountConfig(type, id, path) {} void serializeDiff(YAML::Emitter& out, const SipAccountBaseConfig& def) const; void unserialize(const YAML::Node& node) override; std::map<std::string, std::string> toMap() const override; void fromMap(const std::map<std::string, std::string>&) override; /** * interface name on which this account is bound */ std::string interface {"default"}; /** * Flag which determine if localIpAddress_ or publishedIpAddress_ is used in * sip headers */ bool publishedSameasLocal {true}; std::string publishedIp; /** * Determine if TURN public address resolution is required to register this account. In this * case a TURN server hostname must be specified. */ bool turnEnabled {false}; /** * The TURN server hostname (optional), used to provide the public IP address in case the * softphone stay behind a NAT. */ std::string turnServer; std::string turnServerUserName; std::string turnServerPwd; std::string turnServerRealm; std::string tlsCaListFile; std::string tlsCertificateFile; std::string tlsPrivateKeyFile; std::string tlsPassword; std::string dtmfType {OVERRTP_STR}; /* * Port range for audio RTP ports */ std::pair<uint16_t, uint16_t> audioPortRange {16384, 32766}; /** * Port range for video RTP ports */ std::pair<uint16_t, uint16_t> videoPortRange {49152, (65536) -2}; }; inline void updateRange(uint16_t min, uint16_t max, std::pair<uint16_t, uint16_t>& range) { if (min > 0 and (max > min) and max <= MAX_PORT - 2) { range.first = min; range.second = max; } } }
2,877
C++
.h
76
33.697368
107
0.705059
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
752,065
sipaccount_config.h
savoirfairelinux_jami-daemon/src/sip/sipaccount_config.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 "sipaccountbase_config.h" namespace jami { constexpr static std::string_view ACCOUNT_TYPE_SIP = "SIP"; struct SipAccountConfig : public SipAccountBaseConfig { SipAccountConfig(const std::string& id = {}, const std::filesystem::path& path = {}): SipAccountBaseConfig(std::string(ACCOUNT_TYPE_SIP), id, path) {} void serialize(YAML::Emitter& out) const override; void unserialize(const YAML::Node& node) override; std::map<std::string, std::string> toMap() const override; void fromMap(const std::map<std::string, std::string>&) override; /** * Local port to whih this account is bound */ uint16_t localPort {sip_utils::DEFAULT_SIP_PORT}; /** * Potential ip addresss on which this account is bound */ std::string bindAddress {}; /** * Published port, used only if defined by the user */ uint16_t publishedPort {sip_utils::DEFAULT_SIP_PORT}; /** * interface name on which this account is bound */ std::string interface {dhtnet::ip_utils::DEFAULT_INTERFACE}; /** * Determine if STUN public address resolution is required to register this account. In this * case a STUN server hostname must be specified. */ bool stunEnabled {false}; /** * The STUN server hostname (optional), used to provide the public IP address in case the * softphone stay behind a NAT. */ std::string stunServer {}; /** * Network settings */ unsigned registrationExpire {3600}; bool registrationRefreshEnabled {true}; // If true, the contact addreass and header will be rewritten // using the information received from the registrar. bool allowIPAutoRewrite {true}; /** * Input Outbound Proxy Server Address */ std::string serviceRoute; /** * The TLS listener port */ uint16_t tlsListenerPort {sip_utils::DEFAULT_SIP_TLS_PORT}; bool tlsEnable {false}; std::string tlsMethod; std::string tlsCiphers; std::string tlsServerName; bool tlsVerifyServer {true}; bool tlsVerifyClient {true}; bool tlsRequireClientCertificate {true}; bool tlsDisableSecureDlgCheck {true}; int tlsNegotiationTimeout {2}; /** * Determine if the softphone should fallback on non secured media channel if SRTP negotiation * fails. Make sure other SIP endpoints share the same behavior since it could result in * encrypted data to be played through the audio device. */ bool srtpFallback {false}; /** * Specifies the type of key exchange used for SRTP, if any. * This only determine if the media channel is secured. */ KeyExchangeProtocol srtpKeyExchange {KeyExchangeProtocol::SDES}; bool presenceEnabled {false}; bool publishSupported {false}; bool subscribeSupported {false}; /** * Map of credential for this account */ struct Credentials { std::string realm {}; std::string username {}; std::string password {}; std::string password_h {}; Credentials(const std::string& r, const std::string& u, const std::string& p) : realm(r) , username(u) , password(p) {} Credentials(const std::map<std::string, std::string>& r); std::map<std::string, std::string> toMap() const; void computePasswordHash(); }; std::vector<Credentials> credentials; std::vector<std::map<std::string, std::string>> getCredentials() const; void setCredentials(const std::vector<std::map<std::string, std::string>>& creds); }; }
4,343
C++
.h
114
32.850877
154
0.685023
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
752,066
pres_sub_client.h
savoirfairelinux_jami-daemon/src/sip/pres_sub_client.h
/* * Copyright (C) 2012, 2013 LOTES TM LLC * Author : Andrey Loukhnov <aol.nnov@gmail.com> * Author : Patrick Keroulas <patrick.keroulas@savoirfairelinux.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/>. */ #ifndef PRES_SUB_CLIENT_H #define PRES_SUB_CLIENT_H #include <pjsip-simple/presence.h> #include <pj/timer.h> #include <pj/pool.h> #include <string> #include <pjsip-simple/evsub.h> #include <pjsip-simple/evsub_msg.h> #include <pjsip/sip_endpoint.h> #include <pjsip/sip_transport.h> #include "noncopyable.h" namespace jami { class SIPPresence; class PresSubClient { public: /** * Constructor * @param uri SIP uri of remote user that we want to subscribe, */ PresSubClient(const std::string& uri, SIPPresence* pres); /** * Destructor. * Process the the unsubscription before the destruction. */ ~PresSubClient(); /** * Compare with another pres_client's uris. * @param b Other pres_client pointer */ bool match(PresSubClient* b); /** * Enable the monitoring and report signal to the client. * The PBX server must approve and maintain the subrciption before the pres_client is added in * the pres_client list. * @param flag State of subscription. True if active. */ void enable(bool flag); /** * Get associated parent presence_module */ SIPPresence* getPresence(); /** * Data lock function */ bool lock(); /** * Data unlock function */ void unlock(); /** * Send a SUBCRIBE to the PXB or directly to a pres_client in the IP2IP context. */ bool subscribe(); /** * Send a SUBCRIBE to the PXB or directly to a pres_client in the IP2IP context but * the 0s timeout make the dialog expire immediately. */ bool unsubscribe(); /** * Return the monitor variable. */ bool isSubscribed(); /** * Return the pres_client URI */ std::string_view getURI(); /** * Is the buddy present */ bool isPresent(); /** * A message from the URIs */ std::string_view getLineStatus(); /** * TODO: explain this: */ void incLock() { lock_count_++; } void decLock() { lock_count_--; } private: NON_COPYABLE(PresSubClient); /** * Transaction functions of event subscription client side. */ static void pres_client_evsub_on_state(pjsip_evsub* sub, pjsip_event* event); static void pres_client_evsub_on_tsx_state(pjsip_evsub* sub, pjsip_transaction* tsx, pjsip_event* event); static void 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); static void pres_client_timer_cb(pj_timer_heap_t* th, pj_timer_entry* entry); /** * Plan a retry or a renew a subscription. * @param reschedule Allow for reschedule. * @param msec Delay value in milliseconds. */ void rescheduleTimer(bool reschedule, unsigned msec); /** * Callback after a presence notification was received. * Tranfert info to the SIP account. */ void reportPresence(); /** * Process the un/subscribe request transmission. */ pj_status_t updateSubscription(); /* * Compare the reason of a transaction end with the given string. */ bool isTermReason(const std::string&); /** * return the code after a transaction is terminated. */ unsigned getTermCode(); SIPPresence* pres_; /**< Associated SIPPresence pointer */ pj_str_t uri_; /**< pres_client URI. */ pj_str_t contact_; /**< Contact learned from subscrp. */ pj_str_t display_; /**< pres_client display name. */ pjsip_dialog* dlg_; /**< The underlying dialog. */ pj_bool_t monitored_; /**< Should we monitor? */ pj_str_t name_; /**< pres_client name. */ pj_caching_pool cp_; pj_pool_t* pool_; /**< Pool for this pres_client. */ pjsip_pres_status status_; /**< pres_client presence status. */ pjsip_evsub* sub_; /**< pres_client presence subscription */ unsigned term_code_; /**< Subscription termination code */ pj_str_t term_reason_; /**< Subscription termination reason */ pj_timer_entry timer_; /**< Resubscription timer */ void* user_data_; /**< Application data. */ int lock_count_; int lock_flag_; static int modId_; // used to extract data structure from event_subscription }; } // namespace jami #endif /* PRES_SUB_CLIENT_H */
5,599
C++
.h
159
28.779874
98
0.615668
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
752,067
sdes_negotiator.h
savoirfairelinux_jami-daemon/src/sip/sdes_negotiator.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 "media/media_codec.h" #include <stdexcept> #include <string> #include <vector> using namespace std::literals; namespace jami { /** * General exception object that is thrown when * an error occurred with a regular expression * operation. */ class ParseError : public std::invalid_argument { public: explicit ParseError(const std::string& error) : std::invalid_argument(error) {} }; enum CipherMode { AESCounterMode, AESF8Mode }; enum MACMode { HMACSHA1 }; enum KeyMethod { Inline // url, maybe at some point }; struct CryptoSuiteDefinition { std::string_view name; int masterKeyLength; int masterSaltLength; int srtpLifetime; int srtcpLifetime; CipherMode cipher; int encryptionKeyLength; MACMode mac; int srtpAuthTagLength; int srtcpAuthTagLength; int srtpAuthKeyLength; int srtcpAuthKeyLen; }; /** * List of accepted Crypto-Suites * as defined in RFC4568 (6.2) */ static std::vector<CryptoSuiteDefinition> CryptoSuites = { {"AES_CM_128_HMAC_SHA1_80"sv, 128, 112, 48, 31, AESCounterMode, 128, HMACSHA1, 80, 80, 160, 160}, {"AES_CM_128_HMAC_SHA1_32"sv, 128, 112, 48, 31, AESCounterMode, 128, HMACSHA1, 32, 80, 160, 160}, {"F8_128_HMAC_SHA1_80"sv, 128, 112, 48, 31, AESF8Mode, 128, HMACSHA1, 80, 80, 160, 160}}; class SdesNegotiator { public: SdesNegotiator(); static CryptoAttribute negotiate(const std::vector<std::string>& attributes); inline explicit operator bool() const { return not CryptoSuites.empty(); } private: static std::vector<CryptoAttribute> parse(const std::vector<std::string>& attributes); }; } // namespace jami
2,395
C++
.h
74
29.472973
101
0.732523
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