cleanup: Remove apidsl; remove crypto_memcmp.

* `crypto_memcmp` was replaced by more specific functions. We never want
  to compare arbitrary amounts of data this way. We use these functions
  to compare key material.
* apidsl has been bothering people, so now we un-bother them. You're
  welcome.
* Added the memlock/unlock functions from the New Group Chats branch.
* Remove some system dependencies in crypto_core_mem.c.
* Renamed UPPERCASE_NAMES to Snake_Camel_Case names.
This commit is contained in:
iphydf 2021-12-19 18:38:47 +00:00
parent a42b0d62ae
commit 4746a8b3af
No known key found for this signature in database
GPG Key ID: 3855DBA2D74403C9
23 changed files with 455 additions and 4566 deletions

View File

@ -1,7 +1,7 @@
---
cirrus-ci_task:
container:
image: toxchat/toktok-stack:0.0.27-third_party
image: toxchat/toktok-stack:0.0.28-third_party
cpu: 2
memory: 2G
configure_script:
@ -19,7 +19,7 @@ cirrus-ci_task:
cimple_task:
container:
image: toxchat/toktok-stack:0.0.27-third_party
image: toxchat/toktok-stack:0.0.28-third_party
cpu: 2
memory: 4G
configure_script:

View File

@ -52,7 +52,6 @@ message("SOVERSION: ${SOVERSION}")
#
################################################################################
include(ApiDsl)
include(CTest)
include(ModulePackage)
include(StrictAbi)
@ -240,7 +239,6 @@ set(toxcore_SOURCES ${toxcore_SOURCES}
# LAYER 8: Public API
# -------------------
apidsl(toxcore/tox.api.h)
set(toxcore_SOURCES ${toxcore_SOURCES}
toxcore/tox_api.c
toxcore/tox.c
@ -255,7 +253,6 @@ set(toxcore_API_HEADERS ${toxcore_API_HEADERS} ${toxcore_SOURCE_DIR}/toxcore/tox
################################################################################
if(BUILD_TOXAV)
apidsl(toxav/toxav.api.h)
set(toxcore_SOURCES ${toxcore_SOURCES}
toxav/audio.c
toxav/audio.h
@ -286,7 +283,6 @@ endif()
#
################################################################################
apidsl(toxencryptsave/toxencryptsave.api.h)
set(toxcore_SOURCES ${toxcore_SOURCES}
toxencryptsave/toxencryptsave.c
toxencryptsave/toxencryptsave.h)

View File

@ -1,44 +0,0 @@
################################################################################
#
# :: APIDSL regeneration
#
################################################################################
find_program(APIDSL NAMES
apidsl
apidsl.native
apidsl.byte
${CMAKE_SOURCE_DIR}/../apidsl/apigen.native)
find_program(ASTYLE NAMES
astyle
$ENV{ASTYLE})
function(apidsl)
if(APIDSL AND ASTYLE)
foreach(in_file ${ARGN})
# Get the directory component of the input file name.
if(CMAKE_VERSION VERSION_LESS 3.0)
execute_process(
COMMAND dirname ${in_file}
OUTPUT_VARIABLE dirname
OUTPUT_STRIP_TRAILING_WHITESPACE)
else()
get_filename_component(dirname ${in_file} DIRECTORY)
endif()
# Get the name without extension (i.e. without ".api.h").
get_filename_component(filename ${in_file} NAME_WE)
# Put them together, with the new extension that is ".h".
set(out_file ${CMAKE_SOURCE_DIR}/${dirname}/${filename}.h)
# Run apidsl.
add_custom_command(
OUTPUT ${out_file}
COMMAND "${APIDSL}" "${CMAKE_SOURCE_DIR}/${in_file}"
| "${ASTYLE}" --options="${CMAKE_SOURCE_DIR}/other/astyle/astylerc"
> "${out_file}"
DEPENDS ${in_file})
endforeach()
endif()
endfunction()

View File

@ -4,7 +4,6 @@ set -ex
SOURCE_DIR="$1"
ASTYLE="$2"
APIDSL="$3"
# Go to the source root.
if [ -z "$SOURCE_DIR" ]; then
@ -22,62 +21,6 @@ if ! which "$ASTYLE"; then
exit 1
fi
if ! which "$APIDSL"; then
if [ -f ../apidsl/apigen.native ]; then
APIDSL=../apidsl/apigen.native
else
APIDSL=apidsl_curl
fi
fi
TO_JSON='s/\\/\\\\/g;s/\n/\\n/g;s/"/\\"/g;s/^(.*)$/"$1"/'
FROM_JSON='s/\\"/"/g;s/^"(.*)"$/$1/;s/\\\\/\\/g;s/\\n/\n/g'
apidsl_request() {
TMPFILE=$(mktemp /tmp/apidsl.XXXXXX)
curl -s -o "$TMPFILE" -X POST --data @<(
echo '["Request",'
cat "$2"
echo ']'
) "https://apidsl.herokuapp.com/$1"
if grep '\[1,"' "$TMPFILE" >/dev/null; then
echo "Error: $(grep -o '".*"' /tmp/apidsl-$$ | perl -0777 -pe "$FROM_JSON")" >&2
rm "$TMPFILE"
exit 1
fi
perl -0777 -pe 's/^\[0,(.*)\]$/$1/' "$TMPFILE"
rm "$TMPFILE"
}
apidsl_curl() {
echo "apidsl_curl $*" >&2
apidsl_request "c" <(
apidsl_request "parse" <(
perl -0777 -pe "$TO_JSON" "$1"
)
) | perl -0777 -pe "$FROM_JSON"
}
# Check if apidsl generated sources are up to date.
set +x
"$APIDSL" toxcore/tox.api.h >toxcore/tox.h &
"$APIDSL" toxav/toxav.api.h >toxav/toxav.h &
"$APIDSL" toxencryptsave/toxencryptsave.api.h >toxencryptsave/toxencryptsave.h &
set -x
wait
wait
wait
wait
wait
wait
wait
if grep '<unresolved>' ./*/*.h; then
echo "error: some apidsl references were unresolved"
exit 1
fi
readarray -t CC_SOURCES <<<"$(find . '(' -name '*.cc' ')')"
CC_SOURCES+=(toxcore/crypto_core.c)
CC_SOURCES+=(toxcore/ping_array.c)

View File

@ -115,7 +115,6 @@ cc_library(
"toxav_old.c",
],
hdrs = [
"toxav.api.h",
"toxav.h",
],
visibility = ["//c-toxcore:__subpackages__"],
@ -125,16 +124,11 @@ cc_library(
],
)
CIMPLE_SRCS = glob(
[
"*.c",
"*.h",
],
exclude = ["*.api.h"],
)
sh_library(
name = "cimple_files",
srcs = CIMPLE_SRCS,
srcs = glob([
"*.c",
"*.h",
]),
visibility = ["//c-toxcore/testing:__pkg__"],
)

View File

@ -1,746 +0,0 @@
%{
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright © 2016-2018 The TokTok team.
* Copyright © 2013-2015 Tox project.
*/
#ifndef C_TOXCORE_TOXAV_TOXAV_H
#define C_TOXCORE_TOXAV_TOXAV_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
//!TOKSTYLE-
#ifdef __cplusplus
extern "C" {
#endif
%}
/** \page av Public audio/video API for Tox clients.
*
* This API can handle multiple calls. Each call has its state, in very rare
* occasions the library can change the state of the call without apps knowledge.
*
*/
/** \subsection events Events and callbacks
*
* As in Core API, events are handled by callbacks. One callback can be
* registered per event. All events have a callback function type named
* `toxav_{event}_cb` and a function to register it named `toxav_callback_{event}`.
* Passing a NULL callback will result in no callback being registered for that
* event. Only one callback per event can be registered, so if a client needs
* multiple event listeners, it needs to implement the dispatch functionality
* itself. Unlike Core API, lack of some event handlers will cause the the
* library to drop calls before they are started. Hanging up call from a
* callback causes undefined behaviour.
*
*/
/** \subsection threading Threading implications
*
* Only ${toxAV.iterate} is thread-safe, all other functions must run from the
* tox thread.
*
* Important exceptions are the `*_iterate` and `*_iterate_interval`
* functions. You have to choose either the single thread or the multi thread
* functions and read their documentation.
*
* A common way to run ToxAV (multiple or single instance) is to have a thread,
* separate from tox instance thread, running a simple ${toxAV.iterate} loop,
* sleeping for ${toxAV.iteration_interval} * milliseconds on each iteration.
*
* An important thing to note is that events are triggered from both tox and
* toxav thread (see above). Audio and video receive frame events are triggered
* from toxav thread while all the other events are triggered from tox thread.
*
* Tox thread has priority with mutex mechanisms. Any api function can
* fail if mutexes are held by tox thread in which case they will set SYNC
* error code.
*/
/** \subsection multi-threading Separate audio and video threads
*
* ToxAV supports either a single thread for audio and video or decoding and
* encoding them in separate threads. You have to choose one mode and can not
* mix function calls to those different modes.
*
* For best results use the multi-threaded mode and run the audio thread with
* higher priority than the video thread. This prioritizes audio over video.
*/
/**
* External Tox type.
*/
class tox {
struct this;
}
/**
* ToxAV.
*/
class toxAV {
/**
* The ToxAV instance type. Each ToxAV instance can be bound to only one Tox
* instance, and Tox instance can have only one ToxAV instance. One must make
* sure to close ToxAV instance prior closing Tox instance otherwise undefined
* behaviour occurs. Upon closing of ToxAV instance, all active calls will be
* forcibly terminated without notifying peers.
*
*/
struct this;
/*******************************************************************************
*
* :: Creation and destruction
*
******************************************************************************/
/**
* Start new A/V session. There can only be only one session per Tox instance.
*/
static this new(tox::this *tox) {
NULL,
/**
* Memory allocation failure while trying to allocate structures required for
* the A/V session.
*/
MALLOC,
/**
* Attempted to create a second session for the same Tox instance.
*/
MULTIPLE,
}
/**
* Releases all resources associated with the A/V session.
*
* If any calls were ongoing, these will be forcibly terminated without
* notifying peers. After calling this function, no other functions may be
* called and the av pointer becomes invalid.
*/
void kill();
/**
* Returns the Tox instance the A/V object was created for.
*/
tox::this *tox { get(); }
/*******************************************************************************
*
* :: A/V event loop, single thread
*
******************************************************************************/
/**
* Returns the interval in milliseconds when the next toxav_iterate call should
* be. If no call is active at the moment, this function returns 200.
* This function MUST be called from the same thread as toxav_iterate.
*/
const uint32_t iteration_interval();
/**
* Main loop for the session. This function needs to be called in intervals of
* toxav_iteration_interval() milliseconds. It is best called in the separate
* thread from tox_iterate.
*/
void iterate();
/*******************************************************************************
*
* :: A/V event loop, multiple threads
*
******************************************************************************/
/**
* Returns the interval in milliseconds when the next toxav_audio_iterate call
* should be. If no call is active at the moment, this function returns 200.
* This function MUST be called from the same thread as toxav_audio_iterate.
*/
const uint32_t audio_iteration_interval();
/**
* Main loop for the session. This function needs to be called in intervals of
* toxav_audio_iteration_interval() milliseconds. It is best called in a
* separate thread from tox_iterate and toxav_video_iterate. The thread calling
* this function should have higher priority than the one calling
* toxav_video_iterate to prioritize audio over video.
*/
void audio_iterate();
/**
* Returns the interval in milliseconds when the next toxav_video_iterate call
* should be. If no call is active at the moment, this function returns 200.
* This function MUST be called from the same thread as toxav_video_iterate.
*/
const uint32_t video_iteration_interval();
/**
* Main loop for the session. This function needs to be called in intervals of
* toxav_video_iteration_interval() milliseconds. It is best called in a
* separate thread from tox_iterate and toxav_audio_iterate. The thread calling
* this function should have lower priority than the one calling
* toxav_audio_iterate to prioritize audio over video.
*/
void video_iterate();
/*******************************************************************************
*
* :: Call setup
*
******************************************************************************/
/**
* Call a friend. This will start ringing the friend.
*
* It is the client's responsibility to stop ringing after a certain timeout,
* if such behaviour is desired. If the client does not stop ringing, the
* library will not stop until the friend is disconnected. Audio and video
* receiving are both enabled by default.
*
* @param friend_number The friend number of the friend that should be called.
* @param audio_bit_rate Audio bit rate in Kb/sec. Set this to 0 to disable
* audio sending.
* @param video_bit_rate Video bit rate in Kb/sec. Set this to 0 to disable
* video sending.
*/
bool call(uint32_t friend_number, uint32_t audio_bit_rate, uint32_t video_bit_rate) {
/**
* A resource allocation error occurred while trying to create the structures
* required for the call.
*/
MALLOC,
/**
* Synchronization error occurred.
*/
SYNC,
/**
* The friend number did not designate a valid friend.
*/
FRIEND_NOT_FOUND,
/**
* The friend was valid, but not currently connected.
*/
FRIEND_NOT_CONNECTED,
/**
* Attempted to call a friend while already in an audio or video call with
* them.
*/
FRIEND_ALREADY_IN_CALL,
/**
* Audio or video bit rate is invalid.
*/
INVALID_BIT_RATE,
}
event call {
/**
* The function type for the ${event call} callback.
*
* @param friend_number The friend number from which the call is incoming.
* @param audio_enabled True if friend is sending audio.
* @param video_enabled True if friend is sending video.
*/
typedef void(uint32_t friend_number, bool audio_enabled, bool video_enabled);
}
/**
* Accept an incoming call.
*
* If answering fails for any reason, the call will still be pending and it is
* possible to try and answer it later. Audio and video receiving are both
* enabled by default.
*
* @param friend_number The friend number of the friend that is calling.
* @param audio_bit_rate Audio bit rate in Kb/sec. Set this to 0 to disable
* audio sending.
* @param video_bit_rate Video bit rate in Kb/sec. Set this to 0 to disable
* video sending.
*/
bool answer(uint32_t friend_number, uint32_t audio_bit_rate, uint32_t video_bit_rate) {
/**
* Synchronization error occurred.
*/
SYNC,
/**
* Failed to initialize codecs for call session. Note that codec initiation
* will fail if there is no receive callback registered for either audio or
* video.
*/
CODEC_INITIALIZATION,
/**
* The friend number did not designate a valid friend.
*/
FRIEND_NOT_FOUND,
/**
* The friend was valid, but they are not currently trying to initiate a call.
* This is also returned if this client is already in a call with the friend.
*/
FRIEND_NOT_CALLING,
/**
* Audio or video bit rate is invalid.
*/
INVALID_BIT_RATE,
}
/*******************************************************************************
*
* :: Call state graph
*
******************************************************************************/
bitmask FRIEND_CALL_STATE {
/**
* Set by the AV core if an error occurred on the remote end or if friend
* timed out. This is the final state after which no more state
* transitions can occur for the call. This call state will never be triggered
* in combination with other call states.
*/
ERROR,
/**
* The call has finished. This is the final state after which no more state
* transitions can occur for the call. This call state will never be
* triggered in combination with other call states.
*/
FINISHED,
/**
* The flag that marks that friend is sending audio.
*/
SENDING_A,
/**
* The flag that marks that friend is sending video.
*/
SENDING_V,
/**
* The flag that marks that friend is receiving audio.
*/
ACCEPTING_A,
/**
* The flag that marks that friend is receiving video.
*/
ACCEPTING_V,
}
event call_state {
/**
* The function type for the ${event call_state} callback.
*
* @param friend_number The friend number for which the call state changed.
* @param state The bitmask of the new call state which is guaranteed to be
* different than the previous state. The state is set to 0 when the call is
* paused. The bitmask represents all the activities currently performed by the
* friend.
*/
typedef void(uint32_t friend_number, uint32_t state);
}
/*******************************************************************************
*
* :: Call control
*
******************************************************************************/
enum class CALL_CONTROL {
/**
* Resume a previously paused call. Only valid if the pause was caused by this
* client, if not, this control is ignored. Not valid before the call is accepted.
*/
RESUME,
/**
* Put a call on hold. Not valid before the call is accepted.
*/
PAUSE,
/**
* Reject a call if it was not answered, yet. Cancel a call after it was
* answered.
*/
CANCEL,
/**
* Request that the friend stops sending audio. Regardless of the friend's
* compliance, this will cause the ${event audio.receive_frame} event to stop being
* triggered on receiving an audio frame from the friend.
*/
MUTE_AUDIO,
/**
* Calling this control will notify client to start sending audio again.
*/
UNMUTE_AUDIO,
/**
* Request that the friend stops sending video. Regardless of the friend's
* compliance, this will cause the ${event video.receive_frame} event to stop being
* triggered on receiving a video frame from the friend.
*/
HIDE_VIDEO,
/**
* Calling this control will notify client to start sending video again.
*/
SHOW_VIDEO,
}
/**
* Sends a call control command to a friend.
*
* @param friend_number The friend number of the friend this client is in a call
* with.
* @param control The control command to send.
*
* @return true on success.
*/
bool call_control(uint32_t friend_number, CALL_CONTROL control) {
/**
* Synchronization error occurred.
*/
SYNC,
/**
* The friend_number passed did not designate a valid friend.
*/
FRIEND_NOT_FOUND,
/**
* This client is currently not in a call with the friend. Before the call is
* answered, only CANCEL is a valid control.
*/
FRIEND_NOT_IN_CALL,
/**
* Happens if user tried to pause an already paused call or if trying to
* resume a call that is not paused.
*/
INVALID_TRANSITION,
}
/*******************************************************************************
*
* :: Controlling bit rates
*
******************************************************************************/
error for bit_rate_set {
/**
* Synchronization error occurred.
*/
SYNC,
/**
* The bit rate passed was not one of the supported values.
*/
INVALID_BIT_RATE,
/**
* The friend_number passed did not designate a valid friend.
*/
FRIEND_NOT_FOUND,
/**
* This client is currently not in a call with the friend.
*/
FRIEND_NOT_IN_CALL,
}
/*******************************************************************************
*
* :: A/V sending
*
******************************************************************************/
error for send_frame {
/**
* In case of video, one of Y, U, or V was NULL. In case of audio, the samples
* data pointer was NULL.
*/
NULL,
/**
* The friend_number passed did not designate a valid friend.
*/
FRIEND_NOT_FOUND,
/**
* This client is currently not in a call with the friend.
*/
FRIEND_NOT_IN_CALL,
/**
* Synchronization error occurred.
*/
SYNC,
/**
* One of the frame parameters was invalid. E.g. the resolution may be too
* small or too large, or the audio sampling rate may be unsupported.
*/
INVALID,
/**
* Either friend turned off audio or video receiving or we turned off sending
* for the said payload.
*/
PAYLOAD_TYPE_DISABLED,
/**
* Failed to push frame through rtp interface.
*/
RTP_FAILED,
}
namespace audio {
/**
* Send an audio frame to a friend.
*
* The expected format of the PCM data is: [s1c1][s1c2][...][s2c1][s2c2][...]...
* Meaning: sample 1 for channel 1, sample 1 for channel 2, ...
* For mono audio, this has no meaning, every sample is subsequent. For stereo,
* this means the expected format is LRLRLR... with samples for left and right
* alternating.
*
* @param friend_number The friend number of the friend to which to send an
* audio frame.
* @param pcm An array of audio samples. The size of this array must be
* sample_count * channels.
* @param sample_count Number of samples in this frame. Valid numbers here are
* ((sample rate) * (audio length) / 1000), where audio length can be
* 2.5, 5, 10, 20, 40 or 60 millseconds.
* @param channels Number of audio channels. Supported values are 1 and 2.
* @param sampling_rate Audio sampling rate used in this frame. Valid sampling
* rates are 8000, 12000, 16000, 24000, or 48000.
*/
bool send_frame(uint32_t friend_number, const int16_t *pcm, size_t sample_count,
uint8_t channels, uint32_t sampling_rate) with error for send_frame;
uint32_t bit_rate {
/**
* Set the bit rate to be used in subsequent video frames.
*
* @param friend_number The friend number of the friend for which to set the
* bit rate.
* @param bit_rate The new audio bit rate in Kb/sec. Set to 0 to disable.
*
* @return true on success.
*/
set(uint32_t friend_number) with error for bit_rate_set;
}
event bit_rate {
/**
* The function type for the ${event bit_rate} callback. The event is triggered
* when the network becomes too saturated for current bit rates at which
* point core suggests new bit rates.
*
* @param friend_number The friend number of the friend for which to set the
* bit rate.
* @param audio_bit_rate Suggested maximum audio bit rate in Kb/sec.
*/
typedef void(uint32_t friend_number, uint32_t audio_bit_rate);
}
}
namespace video {
/**
* Send a video frame to a friend.
*
* Y - plane should be of size: height * width
* U - plane should be of size: (height/2) * (width/2)
* V - plane should be of size: (height/2) * (width/2)
*
* @param friend_number The friend number of the friend to which to send a video
* frame.
* @param width Width of the frame in pixels.
* @param height Height of the frame in pixels.
* @param y Y (Luminance) plane data.
* @param u U (Chroma) plane data.
* @param v V (Chroma) plane data.
*/
bool send_frame(uint32_t friend_number, uint16_t width, uint16_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v) with error for send_frame;
uint32_t bit_rate {
/**
* Set the bit rate to be used in subsequent video frames.
*
* @param friend_number The friend number of the friend for which to set the
* bit rate.
* @param bit_rate The new video bit rate in Kb/sec. Set to 0 to disable.
*
* @return true on success.
*/
set(uint32_t friend_number) with error for bit_rate_set;
}
event bit_rate {
/**
* The function type for the ${event bit_rate} callback. The event is triggered
* when the network becomes too saturated for current bit rates at which
* point core suggests new bit rates.
*
* @param friend_number The friend number of the friend for which to set the
* bit rate.
* @param video_bit_rate Suggested maximum video bit rate in Kb/sec.
*/
typedef void(uint32_t friend_number, uint32_t video_bit_rate);
}
}
/*******************************************************************************
*
* :: A/V receiving
*
******************************************************************************/
namespace audio {
event receive_frame {
/**
* The function type for the ${event receive_frame} callback. The callback can be
* called multiple times per single iteration depending on the amount of queued
* frames in the buffer. The received format is the same as in send function.
*
* @param friend_number The friend number of the friend who sent an audio frame.
* @param pcm An array of audio samples (sample_count * channels elements).
* @param sample_count The number of audio samples per channel in the PCM array.
* @param channels Number of audio channels.
* @param sampling_rate Sampling rate used in this frame.
*
*/
typedef void(uint32_t friend_number, const int16_t *pcm, size_t sample_count,
uint8_t channels, uint32_t sampling_rate);
}
}
namespace video {
event receive_frame {
/**
* The function type for the ${event receive_frame} callback.
*
* The size of plane data is derived from width and height as documented
* below.
*
* Strides represent padding for each plane that may or may not be present.
* You must handle strides in your image processing code. Strides are
* negative if the image is bottom-up hence why you MUST abs() it when
* calculating plane buffer size.
*
* @param friend_number The friend number of the friend who sent a video frame.
* @param width Width of the frame in pixels.
* @param height Height of the frame in pixels.
* @param y Luminosity plane. Size = MAX(width, abs(ystride)) * height.
* @param u U chroma plane. Size = MAX(width/2, abs(ustride)) * (height/2).
* @param v V chroma plane. Size = MAX(width/2, abs(vstride)) * (height/2).
*
* @param ystride Luminosity plane stride.
* @param ustride U chroma plane stride.
* @param vstride V chroma plane stride.
*/
typedef void(uint32_t friend_number, uint16_t width, uint16_t height,
const uint8_t *y, const uint8_t *u, const uint8_t *v,
int32_t ystride, int32_t ustride, int32_t vstride);
}
}
}
%{
/**
* NOTE Compatibility with old toxav group calls. TODO(iphydf): remove
*
* TODO(iphydf): Use proper new API guidelines for these. E.g. don't use inline
* function types, don't have per-callback userdata, especially don't have one
* userdata per group.
*/
/* Create a new toxav group.
*
* return group number on success.
* return -1 on failure.
*
* Audio data callback format:
* audio_callback(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, unsigned int samples, uint8_t channels, uint32_t sample_rate, void *userdata)
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
*/
int toxav_add_av_groupchat(Tox *tox,
void (*audio_callback)(void *, uint32_t, uint32_t, const int16_t *, unsigned int, uint8_t, uint32_t, void *),
void *userdata);
/* Join a AV group (you need to have been invited first.)
*
* returns group number on success
* returns -1 on failure.
*
* Audio data callback format (same as the one for toxav_add_av_groupchat()):
* audio_callback(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, unsigned int samples, uint8_t channels, uint32_t sample_rate, void *userdata)
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
*/
int toxav_join_av_groupchat(Tox *tox, uint32_t friendnumber, const uint8_t *data, uint16_t length,
void (*audio_callback)(void *, uint32_t, uint32_t, const int16_t *, unsigned int, uint8_t, uint32_t, void *),
void *userdata);
/* Send audio to the group chat.
*
* return 0 on success.
* return -1 on failure.
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
*
* Valid number of samples are ((sample rate) * (audio length (Valid ones are: 2.5, 5, 10, 20, 40 or 60 ms)) / 1000)
* Valid number of channels are 1 or 2.
* Valid sample rates are 8000, 12000, 16000, 24000, or 48000.
*
* Recommended values are: samples = 960, channels = 1, sample_rate = 48000
*/
int toxav_group_send_audio(Tox *tox, uint32_t groupnumber, const int16_t *pcm, unsigned int samples, uint8_t channels,
uint32_t sample_rate);
/* Enable A/V in a groupchat.
*
* A/V must be enabled on a groupchat for audio to be sent to it and for
* received audio to be handled.
*
* An A/V group created with toxav_add_av_groupchat or toxav_join_av_groupchat
* will start with A/V enabled.
*
* An A/V group loaded from a savefile will start with A/V disabled.
*
* return 0 on success.
* return -1 on failure.
*
* Audio data callback format (same as the one for toxav_add_av_groupchat()):
* audio_callback(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, unsigned int samples, uint8_t channels, uint32_t sample_rate, void *userdata)
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
*/
int toxav_groupchat_enable_av(Tox *tox, uint32_t groupnumber,
void (*audio_callback)(void *, uint32_t, uint32_t, const int16_t *, unsigned int, uint8_t, uint32_t, void *),
void *userdata);
/* Disable A/V in a groupchat.
*
* return 0 on success.
* return -1 on failure.
*/
int toxav_groupchat_disable_av(Tox *tox, uint32_t groupnumber);
/* Return whether A/V is enabled in the groupchat.
*/
bool toxav_groupchat_av_enabled(Tox *tox, uint32_t groupnumber);
#ifdef __cplusplus
}
#endif
typedef void toxav_group_audio_cb(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, uint32_t samples, uint8_t channels, uint32_t sample_rate, void *user_data);
typedef TOXAV_ERR_CALL Toxav_Err_Call;
typedef TOXAV_ERR_NEW Toxav_Err_New;
typedef TOXAV_ERR_ANSWER Toxav_Err_Answer;
typedef TOXAV_ERR_CALL_CONTROL Toxav_Err_Call_Control;
typedef TOXAV_ERR_BIT_RATE_SET Toxav_Err_Bit_Rate_Set;
typedef TOXAV_ERR_SEND_FRAME Toxav_Err_Send_Frame;
typedef TOXAV_CALL_CONTROL Toxav_Call_Control;
//!TOKSTYLE+
#endif // C_TOXCORE_TOXAV_TOXAV_H
%}

View File

@ -2,26 +2,14 @@
* Copyright © 2016-2018 The TokTok team.
* Copyright © 2013-2015 Tox project.
*/
#ifndef C_TOXCORE_TOXAV_TOXAV_H
#define C_TOXCORE_TOXAV_TOXAV_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
//!TOKSTYLE-
#ifdef __cplusplus
extern "C" {
#endif
/** \page av Public audio/video API for Tox clients.
*
* This API can handle multiple calls. Each call has its state, in very rare
* occasions the library can change the state of the call without apps knowledge.
*
*/
/** \subsection events Events and callbacks
*
* \subsection events Events and callbacks
*
* As in Core API, events are handled by callbacks. One callback can be
* registered per event. All events have a callback function type named
@ -33,8 +21,8 @@ extern "C" {
* library to drop calls before they are started. Hanging up call from a
* callback causes undefined behaviour.
*
*/
/** \subsection threading Threading implications
*
* \subsection threading Threading implications
*
* Only toxav_iterate is thread-safe, all other functions must run from the
* tox thread.
@ -45,7 +33,7 @@ extern "C" {
*
* A common way to run ToxAV (multiple or single instance) is to have a thread,
* separate from tox instance thread, running a simple toxav_iterate loop,
* sleeping for toxav_iteration_interval * milliseconds on each iteration.
* sleeping for `toxav_iteration_interval * milliseconds` on each iteration.
*
* An important thing to note is that events are triggered from both tox and
* toxav thread (see above). Audio and video receive frame events are triggered
@ -54,8 +42,8 @@ extern "C" {
* Tox thread has priority with mutex mechanisms. Any api function can
* fail if mutexes are held by tox thread in which case they will set SYNC
* error code.
*/
/** \subsection multi-threading Separate audio and video threads
*
* \subsection multi-threading Separate audio and video threads
*
* ToxAV supports either a single thread for audio and video or decoding and
* encoding them in separate threads. You have to choose one mode and can not
@ -64,6 +52,17 @@ extern "C" {
* For best results use the multi-threaded mode and run the audio thread with
* higher priority than the video thread. This prioritizes audio over video.
*/
#ifndef C_TOXCORE_TOXAV_TOXAV_H
#define C_TOXCORE_TOXAV_TOXAV_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* External Tox type.
*/
@ -72,16 +71,12 @@ extern "C" {
typedef struct Tox Tox;
#endif /* TOX_DEFINED */
/**
* ToxAV.
*/
/**
* The ToxAV instance type. Each ToxAV instance can be bound to only one Tox
* instance, and Tox instance can have only one ToxAV instance. One must make
* sure to close ToxAV instance prior closing Tox instance otherwise undefined
* behaviour occurs. Upon closing of ToxAV instance, all active calls will be
* forcibly terminated without notifying peers.
*
*/
#ifndef TOXAV_DEFINED
#define TOXAV_DEFINED
@ -97,7 +92,7 @@ typedef struct ToxAV ToxAV;
typedef enum TOXAV_ERR_NEW {
typedef enum Toxav_Err_New {
/**
* The function returned successfully.
@ -120,13 +115,13 @@ typedef enum TOXAV_ERR_NEW {
*/
TOXAV_ERR_NEW_MULTIPLE,
} TOXAV_ERR_NEW;
} Toxav_Err_New;
/**
* Start new A/V session. There can only be only one session per Tox instance.
*/
ToxAV *toxav_new(Tox *tox, TOXAV_ERR_NEW *error);
ToxAV *toxav_new(Tox *tox, Toxav_Err_New *error);
/**
* Releases all resources associated with the A/V session.
@ -215,7 +210,7 @@ void toxav_video_iterate(ToxAV *av);
typedef enum TOXAV_ERR_CALL {
typedef enum Toxav_Err_Call {
/**
* The function returned successfully.
@ -254,7 +249,7 @@ typedef enum TOXAV_ERR_CALL {
*/
TOXAV_ERR_CALL_INVALID_BIT_RATE,
} TOXAV_ERR_CALL;
} Toxav_Err_Call;
/**
@ -272,7 +267,7 @@ typedef enum TOXAV_ERR_CALL {
* video sending.
*/
bool toxav_call(ToxAV *av, uint32_t friend_number, uint32_t audio_bit_rate, uint32_t video_bit_rate,
TOXAV_ERR_CALL *error);
Toxav_Err_Call *error);
/**
* The function type for the call callback.
@ -290,7 +285,7 @@ typedef void toxav_call_cb(ToxAV *av, uint32_t friend_number, bool audio_enabled
*/
void toxav_callback_call(ToxAV *av, toxav_call_cb *callback, void *user_data);
typedef enum TOXAV_ERR_ANSWER {
typedef enum Toxav_Err_Answer {
/**
* The function returned successfully.
@ -325,7 +320,7 @@ typedef enum TOXAV_ERR_ANSWER {
*/
TOXAV_ERR_ANSWER_INVALID_BIT_RATE,
} TOXAV_ERR_ANSWER;
} Toxav_Err_Answer;
/**
@ -342,7 +337,7 @@ typedef enum TOXAV_ERR_ANSWER {
* video sending.
*/
bool toxav_answer(ToxAV *av, uint32_t friend_number, uint32_t audio_bit_rate, uint32_t video_bit_rate,
TOXAV_ERR_ANSWER *error);
Toxav_Err_Answer *error);
/*******************************************************************************
@ -353,7 +348,7 @@ bool toxav_answer(ToxAV *av, uint32_t friend_number, uint32_t audio_bit_rate, ui
enum TOXAV_FRIEND_CALL_STATE {
enum Toxav_Friend_Call_State {
/**
* The empty bit mask. None of the bits specified below are set.
@ -425,7 +420,7 @@ void toxav_callback_call_state(ToxAV *av, toxav_call_state_cb *callback, void *u
typedef enum TOXAV_CALL_CONTROL {
typedef enum Toxav_Call_Control {
/**
* Resume a previously paused call. Only valid if the pause was caused by this
@ -468,10 +463,10 @@ typedef enum TOXAV_CALL_CONTROL {
*/
TOXAV_CALL_CONTROL_SHOW_VIDEO,
} TOXAV_CALL_CONTROL;
} Toxav_Call_Control;
typedef enum TOXAV_ERR_CALL_CONTROL {
typedef enum Toxav_Err_Call_Control {
/**
* The function returned successfully.
@ -500,7 +495,7 @@ typedef enum TOXAV_ERR_CALL_CONTROL {
*/
TOXAV_ERR_CALL_CONTROL_INVALID_TRANSITION,
} TOXAV_ERR_CALL_CONTROL;
} Toxav_Err_Call_Control;
/**
@ -512,7 +507,7 @@ typedef enum TOXAV_ERR_CALL_CONTROL {
*
* @return true on success.
*/
bool toxav_call_control(ToxAV *av, uint32_t friend_number, TOXAV_CALL_CONTROL control, TOXAV_ERR_CALL_CONTROL *error);
bool toxav_call_control(ToxAV *av, uint32_t friend_number, Toxav_Call_Control control, Toxav_Err_Call_Control *error);
/*******************************************************************************
@ -523,7 +518,7 @@ bool toxav_call_control(ToxAV *av, uint32_t friend_number, TOXAV_CALL_CONTROL co
typedef enum TOXAV_ERR_BIT_RATE_SET {
typedef enum Toxav_Err_Bit_Rate_Set {
/**
* The function returned successfully.
@ -550,7 +545,7 @@ typedef enum TOXAV_ERR_BIT_RATE_SET {
*/
TOXAV_ERR_BIT_RATE_SET_FRIEND_NOT_IN_CALL,
} TOXAV_ERR_BIT_RATE_SET;
} Toxav_Err_Bit_Rate_Set;
@ -562,7 +557,7 @@ typedef enum TOXAV_ERR_BIT_RATE_SET {
typedef enum TOXAV_ERR_SEND_FRAME {
typedef enum Toxav_Err_Send_Frame {
/**
* The function returned successfully.
@ -607,13 +602,13 @@ typedef enum TOXAV_ERR_SEND_FRAME {
*/
TOXAV_ERR_SEND_FRAME_RTP_FAILED,
} TOXAV_ERR_SEND_FRAME;
} Toxav_Err_Send_Frame;
/**
* Send an audio frame to a friend.
*
* The expected format of the PCM data is: [s1c1][s1c2][...][s2c1][s2c2][...]...
* The expected format of the PCM data is: `[s1c1][s1c2][...][s2c1][s2c2][...]...`
* Meaning: sample 1 for channel 1, sample 1 for channel 2, ...
* For mono audio, this has no meaning, every sample is subsequent. For stereo,
* this means the expected format is LRLRLR... with samples for left and right
@ -622,16 +617,16 @@ typedef enum TOXAV_ERR_SEND_FRAME {
* @param friend_number The friend number of the friend to which to send an
* audio frame.
* @param pcm An array of audio samples. The size of this array must be
* sample_count * channels.
* `sample_count * channels`.
* @param sample_count Number of samples in this frame. Valid numbers here are
* ((sample rate) * (audio length) / 1000), where audio length can be
* `((sample rate) * (audio length) / 1000)`, where audio length can be
* 2.5, 5, 10, 20, 40 or 60 millseconds.
* @param channels Number of audio channels. Supported values are 1 and 2.
* @param sampling_rate Audio sampling rate used in this frame. Valid sampling
* rates are 8000, 12000, 16000, 24000, or 48000.
*/
bool toxav_audio_send_frame(ToxAV *av, uint32_t friend_number, const int16_t *pcm, size_t sample_count,
uint8_t channels, uint32_t sampling_rate, TOXAV_ERR_SEND_FRAME *error);
uint8_t channels, uint32_t sampling_rate, Toxav_Err_Send_Frame *error);
/**
* Set the bit rate to be used in subsequent video frames.
@ -642,7 +637,7 @@ bool toxav_audio_send_frame(ToxAV *av, uint32_t friend_number, const int16_t *pc
*
* @return true on success.
*/
bool toxav_audio_set_bit_rate(ToxAV *av, uint32_t friend_number, uint32_t bit_rate, TOXAV_ERR_BIT_RATE_SET *error);
bool toxav_audio_set_bit_rate(ToxAV *av, uint32_t friend_number, uint32_t bit_rate, Toxav_Err_Bit_Rate_Set *error);
/**
* The function type for the audio_bit_rate callback. The event is triggered
@ -665,9 +660,9 @@ void toxav_callback_audio_bit_rate(ToxAV *av, toxav_audio_bit_rate_cb *callback,
/**
* Send a video frame to a friend.
*
* Y - plane should be of size: height * width
* U - plane should be of size: (height/2) * (width/2)
* V - plane should be of size: (height/2) * (width/2)
* Y - plane should be of size: `height * width`
* U - plane should be of size: `(height/2) * (width/2)`
* V - plane should be of size: `(height/2) * (width/2)`
*
* @param friend_number The friend number of the friend to which to send a video
* frame.
@ -678,7 +673,7 @@ void toxav_callback_audio_bit_rate(ToxAV *av, toxav_audio_bit_rate_cb *callback,
* @param v V (Chroma) plane data.
*/
bool toxav_video_send_frame(ToxAV *av, uint32_t friend_number, uint16_t width, uint16_t height, const uint8_t *y,
const uint8_t *u, const uint8_t *v, TOXAV_ERR_SEND_FRAME *error);
const uint8_t *u, const uint8_t *v, Toxav_Err_Send_Frame *error);
/**
* Set the bit rate to be used in subsequent video frames.
@ -689,7 +684,7 @@ bool toxav_video_send_frame(ToxAV *av, uint32_t friend_number, uint16_t width, u
*
* @return true on success.
*/
bool toxav_video_set_bit_rate(ToxAV *av, uint32_t friend_number, uint32_t bit_rate, TOXAV_ERR_BIT_RATE_SET *error);
bool toxav_video_set_bit_rate(ToxAV *av, uint32_t friend_number, uint32_t bit_rate, Toxav_Err_Bit_Rate_Set *error);
/**
* The function type for the video_bit_rate callback. The event is triggered
@ -724,7 +719,7 @@ void toxav_callback_video_bit_rate(ToxAV *av, toxav_video_bit_rate_cb *callback,
* frames in the buffer. The received format is the same as in send function.
*
* @param friend_number The friend number of the friend who sent an audio frame.
* @param pcm An array of audio samples (sample_count * channels elements).
* @param pcm An array of audio samples (`sample_count * channels` elements).
* @param sample_count The number of audio samples per channel in the PCM array.
* @param channels Number of audio channels.
* @param sampling_rate Sampling rate used in this frame.
@ -754,9 +749,9 @@ void toxav_callback_audio_receive_frame(ToxAV *av, toxav_audio_receive_frame_cb
* @param friend_number The friend number of the friend who sent a video frame.
* @param width Width of the frame in pixels.
* @param height Height of the frame in pixels.
* @param y Luminosity plane. Size = MAX(width, abs(ystride)) * height.
* @param u U chroma plane. Size = MAX(width/2, abs(ustride)) * (height/2).
* @param v V chroma plane. Size = MAX(width/2, abs(vstride)) * (height/2).
* @param y Luminosity plane. `Size = MAX(width, abs(ystride)) * height`.
* @param u U chroma plane. `Size = MAX(width/2, abs(ustride)) * (height/2)`.
* @param v V chroma plane. `Size = MAX(width/2, abs(vstride)) * (height/2)`.
*
* @param ystride Luminosity plane stride.
* @param ustride U chroma plane stride.
@ -773,49 +768,48 @@ typedef void toxav_video_receive_frame_cb(ToxAV *av, uint32_t friend_number, uin
*/
void toxav_callback_video_receive_frame(ToxAV *av, toxav_video_receive_frame_cb *callback, void *user_data);
/**
/***
* NOTE Compatibility with old toxav group calls. TODO(iphydf): remove
*
* TODO(iphydf): Use proper new API guidelines for these. E.g. don't use inline
* function types, don't have per-callback userdata, especially don't have one
* userdata per group.
*/
// TODO(iphydf): Use this better typed one instead of the void-pointer one below.
typedef void toxav_group_audio_cb(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm,
uint32_t samples, uint8_t channels, uint32_t sample_rate, void *user_data);
typedef void toxav_audio_data_cb(void *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm,
uint32_t samples, uint8_t channels, uint32_t sample_rate, void *userdata);
/* Create a new toxav group.
*
* return group number on success.
* return -1 on failure.
*
* Audio data callback format:
* audio_callback(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, unsigned int samples, uint8_t channels, uint32_t sample_rate, void *userdata)
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
* Note that total size of pcm in bytes is equal to `samples * channels * sizeof(int16_t)`.
*/
int toxav_add_av_groupchat(Tox *tox,
void (*audio_callback)(void *, uint32_t, uint32_t, const int16_t *, unsigned int, uint8_t, uint32_t, void *),
void *userdata);
int toxav_add_av_groupchat(Tox *tox, toxav_audio_data_cb *audio_callback, void *userdata);
/* Join a AV group (you need to have been invited first.)
*
* returns group number on success
* returns -1 on failure.
*
* Audio data callback format (same as the one for toxav_add_av_groupchat()):
* audio_callback(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, unsigned int samples, uint8_t channels, uint32_t sample_rate, void *userdata)
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
* Note that total size of pcm in bytes is equal to `samples * channels * sizeof(int16_t)`.
*/
int toxav_join_av_groupchat(Tox *tox, uint32_t friendnumber, const uint8_t *data, uint16_t length,
void (*audio_callback)(void *, uint32_t, uint32_t, const int16_t *, unsigned int, uint8_t, uint32_t, void *),
void *userdata);
toxav_audio_data_cb *audio_callback, void *userdata);
/* Send audio to the group chat.
*
* return 0 on success.
* return -1 on failure.
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
* Note that total size of pcm in bytes is equal to `samples * channels * sizeof(int16_t)`.
*
* Valid number of samples are ((sample rate) * (audio length (Valid ones are: 2.5, 5, 10, 20, 40 or 60 ms)) / 1000)
* Valid number of samples are `(sample rate) * (audio length) / 1000` (Valid audio lengths are: 2.5, 5, 10, 20, 40 or 60 ms)
* Valid number of channels are 1 or 2.
* Valid sample rates are 8000, 12000, 16000, 24000, or 48000.
*
@ -829,7 +823,7 @@ int toxav_group_send_audio(Tox *tox, uint32_t groupnumber, const int16_t *pcm, u
* A/V must be enabled on a groupchat for audio to be sent to it and for
* received audio to be handled.
*
* An A/V group created with toxav_add_av_groupchat or toxav_join_av_groupchat
* An A/V group created with `toxav_add_av_groupchat` or `toxav_join_av_groupchat`
* will start with A/V enabled.
*
* An A/V group loaded from a savefile will start with A/V disabled.
@ -837,14 +831,10 @@ int toxav_group_send_audio(Tox *tox, uint32_t groupnumber, const int16_t *pcm, u
* return 0 on success.
* return -1 on failure.
*
* Audio data callback format (same as the one for toxav_add_av_groupchat()):
* audio_callback(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm, unsigned int samples, uint8_t channels, uint32_t sample_rate, void *userdata)
*
* Note that total size of pcm in bytes is equal to (samples * channels * sizeof(int16_t)).
* Note that total size of pcm in bytes is equal to `samples * channels * sizeof(int16_t)`.
*/
int toxav_groupchat_enable_av(Tox *tox, uint32_t groupnumber,
void (*audio_callback)(void *, uint32_t, uint32_t, const int16_t *, unsigned int, uint8_t, uint32_t, void *),
void *userdata);
toxav_audio_data_cb *audio_callback, void *userdata);
/* Disable A/V in a groupchat.
*
@ -861,16 +851,16 @@ bool toxav_groupchat_av_enabled(Tox *tox, uint32_t groupnumber);
}
#endif
typedef void toxav_group_audio_cb(Tox *tox, uint32_t groupnumber, uint32_t peernumber, const int16_t *pcm,
uint32_t samples, uint8_t channels, uint32_t sample_rate, void *user_data);
//!TOKSTYLE-
typedef TOXAV_ERR_CALL Toxav_Err_Call;
typedef TOXAV_ERR_NEW Toxav_Err_New;
typedef TOXAV_ERR_ANSWER Toxav_Err_Answer;
typedef TOXAV_ERR_CALL_CONTROL Toxav_Err_Call_Control;
typedef TOXAV_ERR_BIT_RATE_SET Toxav_Err_Bit_Rate_Set;
typedef TOXAV_ERR_SEND_FRAME Toxav_Err_Send_Frame;
typedef TOXAV_CALL_CONTROL Toxav_Call_Control;
typedef Toxav_Err_Call TOXAV_ERR_CALL;
typedef Toxav_Err_New TOXAV_ERR_NEW;
typedef Toxav_Err_Answer TOXAV_ERR_ANSWER;
typedef Toxav_Err_Call_Control TOXAV_ERR_CALL_CONTROL;
typedef Toxav_Err_Bit_Rate_Set TOXAV_ERR_BIT_RATE_SET;
typedef Toxav_Err_Send_Frame TOXAV_ERR_SEND_FRAME;
typedef Toxav_Call_Control TOXAV_CALL_CONTROL;
typedef enum Toxav_Friend_Call_State TOXAV_FRIEND_CALL_STATE;
//!TOKSTYLE+

View File

@ -323,16 +323,11 @@ cc_library(
],
)
CIMPLE_SRCS = glob(
[
"*.c",
"*.h",
],
exclude = ["*.api.h"],
)
sh_library(
name = "cimple_files",
srcs = CIMPLE_SRCS,
srcs = glob([
"*.c",
"*.h",
]),
visibility = ["//c-toxcore/testing:__pkg__"],
)

View File

@ -9,6 +9,9 @@
#define C_TOXCORE_TOXCORE_CCOMPAT_H
#include <assert.h>
#include <stdbool.h>
bool unused_for_tokstyle(void);
//!TOKSTYLE-

View File

@ -16,7 +16,7 @@
#include "ccompat.h"
#ifndef VANILLA_NACL
/* We use libsodium by default. */
// We use libsodium by default.
#include <sodium.h>
#else
#include <crypto_box.h>
@ -29,7 +29,6 @@
#define crypto_box_MACBYTES (crypto_box_ZEROBYTES - crypto_box_BOXZEROBYTES)
#endif
//!TOKSTYLE-
static_assert(CRYPTO_PUBLIC_KEY_SIZE == crypto_box_PUBLICKEYBYTES,
"CRYPTO_PUBLIC_KEY_SIZE should be equal to crypto_box_PUBLICKEYBYTES");
static_assert(CRYPTO_SECRET_KEY_SIZE == crypto_box_SECRETKEYBYTES,
@ -48,7 +47,6 @@ static_assert(CRYPTO_SHA512_SIZE == crypto_hash_sha512_BYTES,
"CRYPTO_SHA512_SIZE should be equal to crypto_hash_sha512_BYTES");
static_assert(CRYPTO_PUBLIC_KEY_SIZE == 32,
"CRYPTO_PUBLIC_KEY_SIZE is required to be 32 bytes for public_key_cmp to work");
//!TOKSTYLE+
static uint8_t *crypto_malloc(size_t bytes)
{
@ -69,6 +67,15 @@ int32_t public_key_cmp(const uint8_t *pk1, const uint8_t *pk2)
return crypto_verify_32(pk1, pk2);
}
int32_t crypto_sha512_cmp(const uint8_t *cksum1, const uint8_t *cksum2)
{
#ifndef VANILLA_NACL
return crypto_verify_64(cksum1, cksum2);
#else
return crypto_verify_32(cksum1, cksum2) && crypto_verify_32(cksum1 + 8, cksum2 + 8);
#endif
}
uint8_t random_u08(void)
{
uint8_t randnum;

View File

@ -18,12 +18,12 @@ extern "C" {
#endif
/**
* The number of bytes in a Tox public key.
* The number of bytes in a Tox public key used for encryption.
*/
#define CRYPTO_PUBLIC_KEY_SIZE 32
/**
* The number of bytes in a Tox secret key.
* The number of bytes in a Tox secret key used for encryption.
*/
#define CRYPTO_SECRET_KEY_SIZE 32
@ -58,17 +58,6 @@ extern "C" {
*/
#define CRYPTO_SHA512_SIZE 64
/**
* A `memcmp`-like function whose running time does not depend on the input
* bytes, only on the input length. Useful to compare sensitive data where
* timing attacks could reveal that data.
*
* This means for instance that comparing "aaaa" and "aaaa" takes 4 time, and
* "aaaa" and "baaa" also takes 4 time. With a regular `memcmp`, the latter may
* take 1 time, because it immediately knows that the two strings are not equal.
*/
int32_t crypto_memcmp(const uint8_t *p1, const uint8_t *p2, size_t length);
/**
* A `bzero`-like function which won't be optimised away by the compiler. Some
* compilers will inline `bzero` or `memset` if they can prove that there will
@ -95,6 +84,14 @@ void crypto_sha512(uint8_t *hash, const uint8_t *data, size_t length);
*/
int32_t public_key_cmp(const uint8_t *pk1, const uint8_t *pk2);
/**
* Compare 2 SHA512 checksums of length CRYPTO_SHA512_SIZE, not vulnerable to
* timing attacks.
*
* @return 0 if both mem locations of length are equal, -1 if they are not.
*/
int32_t crypto_sha512_cmp(const uint8_t *cksum1, const uint8_t *cksum2);
/**
* Return a random 8 bit integer.
*/
@ -214,6 +211,26 @@ void increment_nonce_number(uint8_t *nonce, uint32_t increment);
*/
void new_symmetric_key(uint8_t *key);
/**
* Locks `length` bytes of memory pointed to by `data`. This will attempt to prevent
* the specified memory region from being swapped to disk.
*
* Returns true on success.
*/
bool crypto_memlock(void *data, size_t length);
/**
* Unlocks `length` bytes of memory pointed to by `data`. This allows the specified
* memory region to be swapped to disk.
*
* This function call has the side effect of zeroing the specified memory region
* whether or not it succeeds. Therefore it should only be used once the memory
* is no longer in use.
*
* Returns true on success.
*/
bool crypto_memunlock(void *data, size_t length);
#ifdef __cplusplus
} // extern "C"
#endif

View File

@ -1,42 +1,13 @@
/* SPDX-License-Identifier: ISC
* Copyright © 2016-2021 The TokTok team.
* Copyright © 2013-2016 Frank Denis <j at pureftpd dot org>
*/
/*
* ISC License
*
* Copyright (c) 2013-2016
* Frank Denis <j at pureftpd dot org>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// For explicit_bzero.
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE
#endif
#include "crypto_core.h"
#ifndef VANILLA_NACL
/* We use libsodium by default. */
// We use libsodium by default.
#include <sodium.h>
#else
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
#include <windows.h>
#include <wincrypt.h>
#endif
#include <string.h>
#endif
@ -45,51 +16,52 @@ void crypto_memzero(void *data, size_t length)
{
#ifndef VANILLA_NACL
sodium_memzero(data, length);
#elif defined(_WIN32)
SecureZeroMemory(data, length);
#elif defined(HAVE_MEMSET_S)
if (length > 0U) {
errno_t code = memset_s(data, (rsize_t) length, 0, (rsize_t) length);
if (code != 0) {
abort(); /* LCOV_EXCL_LINE */
}
}
#elif defined(HAVE_EXPLICIT_BZERO)
explicit_bzero(data, length);
#else
//!TOKSTYLE-
volatile uint8_t *volatile pnt = data;
//!TOKSTYLE+
size_t i = (size_t) 0U;
while (i < length) {
pnt[i] = 0U;
++i;
}
memset(data, 0, length);
#endif
}
int32_t crypto_memcmp(const uint8_t *p1, const uint8_t *p2, size_t length)
/**
* Locks `length` bytes of memory pointed to by `data`. This will attempt to prevent
* the specified memory region from being swapped to disk.
*
* Returns true on success.
*/
bool crypto_memlock(void *data, size_t length)
{
#ifndef VANILLA_NACL
return sodium_memcmp(p1, p2, length);
#else
//!TOKSTYLE-
const volatile uint8_t *volatile b1 = p1;
const volatile uint8_t *volatile b2 = p2;
//!TOKSTYLE+
size_t i;
uint8_t d = (uint8_t) 0U;
for (i = 0U; i < length; ++i) {
d |= b1[i] ^ b2[i];
if (sodium_mlock(data, length) != 0) {
return false;
}
return (1 & ((d - 1) >> 8)) - 1;
return true;
#else
return false;
#endif
}
/**
* Unlocks `length` bytes of memory pointed to by `data`. This allows the specified
* memory region to be swapped to disk.
*
* This function call has the side effect of zeroing the specified memory region
* whether or not it succeeds. Therefore it should only be used once the memory
* is no longer in use.
*
* Return 0 on success.
* Return -1 on failure.
*/
bool crypto_memunlock(void *data, size_t length)
{
#ifndef VANILLA_NACL
if (sodium_munlock(data, length) != 0) {
return false;
}
return true;
#else
return false;
#endif
}

View File

@ -7,88 +7,6 @@
namespace {
enum {
/**
* The size of the arrays to compare. This was chosen to take around 2000
* CPU clocks on x86_64.
*
* This is 1MiB.
*/
CRYPTO_TEST_MEMCMP_SIZE = 1024 * 1024,
/**
* The number of times we run memcmp in the test.
*
* We compute the median time taken to reduce error margins.
*/
CRYPTO_TEST_MEMCMP_ITERATIONS = 500,
/**
* The margin of error (in clocks) we allow for this test.
*
* Should be within 0.5% of ~2000 CPU clocks. In reality, the code is much
* more precise and is usually within 1 CPU clock.
*/
CRYPTO_TEST_MEMCMP_EPS = 10,
};
clock_t memcmp_time(uint8_t const *a, uint8_t const *b, size_t len) {
clock_t start = clock();
volatile int result = crypto_memcmp(a, b, len);
(void)result;
return clock() - start;
}
/**
* This function performs the actual timing. It interleaves comparison of
* equal and non-equal arrays to reduce the influence of external effects
* such as the machine being a little more busy 1 second later.
*/
std::pair<clock_t, clock_t> memcmp_median(uint8_t const *src, uint8_t const *same,
uint8_t const *not_same, size_t len) {
clock_t same_results[CRYPTO_TEST_MEMCMP_ITERATIONS];
clock_t not_same_results[CRYPTO_TEST_MEMCMP_ITERATIONS];
for (size_t i = 0; i < CRYPTO_TEST_MEMCMP_ITERATIONS; i++) {
same_results[i] = memcmp_time(src, same, len);
not_same_results[i] = memcmp_time(src, not_same, len);
}
std::sort(same_results, same_results + CRYPTO_TEST_MEMCMP_ITERATIONS);
clock_t const same_median = same_results[CRYPTO_TEST_MEMCMP_ITERATIONS / 2];
std::sort(not_same_results, not_same_results + CRYPTO_TEST_MEMCMP_ITERATIONS);
clock_t const not_same_median = not_same_results[CRYPTO_TEST_MEMCMP_ITERATIONS / 2];
return {same_median, not_same_median};
}
/**
* This test checks whether crypto_memcmp takes the same time for equal and
* non-equal chunks of memory.
*/
TEST(CryptoCore, MemcmpTimingIsDataIndependent) {
// A random piece of memory.
std::vector<uint8_t> src(CRYPTO_TEST_MEMCMP_SIZE);
random_bytes(src.data(), CRYPTO_TEST_MEMCMP_SIZE);
// A separate piece of memory containing the same data.
std::vector<uint8_t> same = src;
// Another piece of memory containing different data.
std::vector<uint8_t> not_same(CRYPTO_TEST_MEMCMP_SIZE);
random_bytes(not_same.data(), CRYPTO_TEST_MEMCMP_SIZE);
// Once we have C++17:
// auto const [same_median, not_same_median] =
auto const result =
memcmp_median(src.data(), same.data(), not_same.data(), CRYPTO_TEST_MEMCMP_SIZE);
clock_t const delta =
std::max(result.first, result.second) - std::min(result.first, result.second);
EXPECT_LT(delta, CRYPTO_TEST_MEMCMP_EPS)
<< "Delta time is too long (" << delta << " >= " << CRYPTO_TEST_MEMCMP_EPS << ")\n"
<< "Time of the same data comparison: " << result.first << " clocks\n"
<< "Time of the different data comparison: " << result.second << " clocks";
}
TEST(CryptoCore, IncrementNonce) {
using Nonce = std::array<uint8_t, CRYPTO_NONCE_SIZE>;
Nonce nonce{};

View File

@ -54,6 +54,14 @@ typedef enum Peer_Id {
#define MIN_MESSAGE_PACKET_LEN (sizeof(uint16_t) * 2 + sizeof(uint32_t) + 1)
static_assert(GROUP_ID_LENGTH == CRYPTO_PUBLIC_KEY_SIZE,
"GROUP_ID_LENGTH should be equal to CRYPTO_PUBLIC_KEY_SIZE");
static bool group_id_eq(const uint8_t *a, const uint8_t *b)
{
return public_key_cmp(a, b) == 0;
}
/* return false if the groupnumber is not valid.
* return true if the groupnumber is valid.
*/
@ -197,7 +205,7 @@ static int frozen_in_group(const Group_c *g, const uint8_t *real_pk)
static int32_t get_group_num(const Group_Chats *g_c, const uint8_t type, const uint8_t *id)
{
for (uint16_t i = 0; i < g_c->num_chats; ++i) {
if (g_c->chats[i].type == type && crypto_memcmp(g_c->chats[i].id, id, GROUP_ID_LENGTH) == 0) {
if (g_c->chats[i].type == type && group_id_eq(g_c->chats[i].id, id)) {
return i;
}
}
@ -208,7 +216,7 @@ static int32_t get_group_num(const Group_Chats *g_c, const uint8_t type, const u
int32_t conference_by_id(const Group_Chats *g_c, const uint8_t *id)
{
for (uint16_t i = 0; i < g_c->num_chats; ++i) {
if (crypto_memcmp(g_c->chats[i].id, id, GROUP_ID_LENGTH) == 0) {
if (group_id_eq(g_c->chats[i].id, id)) {
return i;
}
}
@ -1948,7 +1956,7 @@ static void handle_friend_invite_packet(Messenger *m, uint32_t friendnumber, con
return;
}
if (crypto_memcmp(data + 1 + sizeof(uint16_t) * 2 + 1, g->id, GROUP_ID_LENGTH) != 0) {
if (!group_id_eq(data + 1 + sizeof(uint16_t) * 2 + 1, g->id)) {
return;
}

View File

@ -8,6 +8,11 @@
#if !defined(OS_WIN32) && (defined(_WIN32) || defined(__WIN32__) || defined(WIN32))
#define OS_WIN32
#endif
#include "mono_time.h"
#ifdef OS_WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
@ -21,8 +26,6 @@
#include <sys/time.h>
#endif
#include "mono_time.h"
#include <pthread.h>
#include <stdlib.h>
#include <time.h>

View File

@ -535,8 +535,7 @@ static int handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t
return -1;
}
if (crypto_memcmp(cookie_hash, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE,
CRYPTO_SHA512_SIZE) != 0) {
if (crypto_sha512_cmp(cookie_hash, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE) != 0) {
return -1;
}

View File

@ -6,6 +6,7 @@
/*
* Functions for the core networking.
*/
#ifdef __APPLE__
#define _DARWIN_C_SOURCE
#endif
@ -29,12 +30,12 @@
#define OS_WIN32
#endif
#ifdef OS_WIN32
#ifndef WINVER
#if defined(OS_WIN32) && !defined(WINVER)
// Windows XP
#define WINVER 0x0501
#endif
#endif
#include "network.h"
#ifdef PLAN9
#include <u.h> // Plan 9 requires this is imported first
@ -42,7 +43,7 @@
#include <libc.h>
#endif
#ifdef OS_WIN32 /* Put win32 includes here */
#ifdef OS_WIN32 // Put win32 includes here
// The mingw32/64 Windows library warns about including winsock2.h after
// windows.h even though with the above it's a valid thing to do. So, to make
// mingw32 headers happy, we include winsock2.h first.
@ -52,15 +53,12 @@
#include <ws2tcpip.h>
#endif
#include "network.h"
#ifdef __APPLE__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#if !defined(OS_WIN32)
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
@ -77,6 +75,33 @@
#include <sys/filio.h>
#endif
#else
#ifndef IPV6_V6ONLY
#define IPV6_V6ONLY 27
#endif
#endif
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "logger.h"
#include "mono_time.h"
#include "util.h"
// Disable MSG_NOSIGNAL on systems not supporting it, e.g. Windows, FreeBSD
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
#ifndef IPV6_ADD_MEMBERSHIP
#ifdef IPV6_JOIN_GROUP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#endif
#if !defined(OS_WIN32)
#define TOX_EWOULDBLOCK EWOULDBLOCK
static const char *inet_ntop4(const struct in_addr *addr, char *buf, size_t bufsize)
@ -170,32 +195,10 @@ static int inet_pton6(const char *addrString, struct in6_addr *addrbuf)
#endif
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "logger.h"
#include "mono_time.h"
#include "util.h"
// Disable MSG_NOSIGNAL on systems not supporting it, e.g. Windows, FreeBSD
#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
#ifndef IPV6_ADD_MEMBERSHIP
#ifdef IPV6_JOIN_GROUP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#endif
//!TOKSTYLE-
static_assert(TOX_INET6_ADDRSTRLEN >= INET6_ADDRSTRLEN,
"TOX_INET6_ADDRSTRLEN should be greater or equal to INET6_ADDRSTRLEN (#INET6_ADDRSTRLEN)");
static_assert(TOX_INET_ADDRSTRLEN >= INET_ADDRSTRLEN,
"TOX_INET_ADDRSTRLEN should be greater or equal to INET_ADDRSTRLEN (#INET_ADDRSTRLEN)");
//!TOKSTYLE+
static int make_proto(int proto)
{

View File

@ -22,10 +22,8 @@
#define DATA_REQUEST_MIN_SIZE ONION_DATA_REQUEST_MIN_SIZE
#define DATA_REQUEST_MIN_SIZE_RECV (DATA_REQUEST_MIN_SIZE + ONION_RETURN_3)
//!TOKSTYLE-
static_assert(ONION_PING_ID_SIZE == CRYPTO_PUBLIC_KEY_SIZE,
"announce response packets assume that ONION_PING_ID_SIZE is equal to CRYPTO_PUBLIC_KEY_SIZE");
//!TOKSTYLE+
typedef struct Onion_Announce_Entry {
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE];
@ -47,6 +45,11 @@ struct Onion_Announce {
Shared_Keys shared_keys_recv;
};
static bool onion_ping_id_eq(const uint8_t *a, const uint8_t *b)
{
return public_key_cmp(a, b) == 0;
}
uint8_t *onion_announce_entry_public_key(Onion_Announce *onion_a, uint32_t entry)
{
return onion_a->entries[entry].public_key;
@ -390,8 +393,8 @@ static int handle_announce_request(void *object, IP_Port source, const uint8_t *
uint8_t *data_public_key = plain + ONION_PING_ID_SIZE + CRYPTO_PUBLIC_KEY_SIZE;
if (crypto_memcmp(ping_id1, plain, ONION_PING_ID_SIZE) == 0
|| crypto_memcmp(ping_id2, plain, ONION_PING_ID_SIZE) == 0) {
if (onion_ping_id_eq(ping_id1, plain)
|| onion_ping_id_eq(ping_id2, plain)) {
index = add_to_entries(onion_a, source, packet_public_key, data_public_key,
packet + (ANNOUNCE_REQUEST_SIZE_RECV - ONION_RETURN_3));
} else {

File diff suppressed because it is too large Load Diff

View File

@ -6,11 +6,9 @@
/*
* The Tox public API.
*/
#ifndef __cplusplus
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#endif
#endif
#include "tox.h"
#include "tox_private.h"
@ -33,7 +31,6 @@
} \
} while (0)
//!TOKSTYLE-
static_assert(TOX_HASH_LENGTH == CRYPTO_SHA256_SIZE,
"TOX_HASH_LENGTH is assumed to be equal to CRYPTO_SHA256_SIZE");
static_assert(FILE_ID_LENGTH == CRYPTO_SYMMETRIC_KEY_SIZE,
@ -50,7 +47,6 @@ static_assert(TOX_MAX_NAME_LENGTH == MAX_NAME_LENGTH,
"TOX_MAX_NAME_LENGTH is assumed to be equal to MAX_NAME_LENGTH");
static_assert(TOX_MAX_STATUS_MESSAGE_LENGTH == MAX_STATUSMESSAGE_LENGTH,
"TOX_MAX_STATUS_MESSAGE_LENGTH is assumed to be equal to MAX_STATUSMESSAGE_LENGTH");
//!TOKSTYLE+
struct Tox {
// XXX: Messenger *must* be the first member, because toxav casts its
@ -439,7 +435,7 @@ Tox *tox_new(const struct Tox_Options *options, Tox_Err_New *error)
return nullptr;
}
if (crypto_memcmp(tox_options_get_savedata_data(opts), TOX_ENC_SAVE_MAGIC_NUMBER, TOX_ENC_SAVE_MAGIC_LENGTH) == 0) {
if (memcmp(tox_options_get_savedata_data(opts), TOX_ENC_SAVE_MAGIC_NUMBER, TOX_ENC_SAVE_MAGIC_LENGTH) == 0) {
SET_ERROR_PARAMETER(error, TOX_ERR_NEW_LOAD_ENCRYPTED);
tox_options_free(default_options);
free(tox);

File diff suppressed because it is too large Load Diff

View File

@ -1,311 +0,0 @@
%{
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright © 2016-2018 The TokTok team.
* Copyright © 2013-2016 Tox Developers.
*/
/*
* Batch encryption functions.
*/
#ifndef C_TOXCORE_TOXENCRYPTSAVE_TOXENCRYPTSAVE_H
#define C_TOXCORE_TOXENCRYPTSAVE_TOXENCRYPTSAVE_H
//!TOKSTYLE-
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
%}
/*******************************************************************************
*
* This module is organized into two parts.
*
* 1. A simple API operating on plain text/cipher text data and a password to
* encrypt or decrypt it.
* 2. A more advanced API that splits key derivation and encryption into two
* separate function calls.
*
* The first part is implemented in terms of the second part and simply calls
* the separate functions in sequence. Since key derivation is very expensive
* compared to the actual encryption, clients that do a lot of crypto should
* prefer the advanced API and reuse pass-key objects.
*
* To use the second part, first derive an encryption key from a password with
* ${tox.pass_Key.derive}, then use the derived key to encrypt the data.
*
* The encrypted data is prepended with a magic number, to aid validity
* checking (no guarantees are made of course). Any data to be decrypted must
* start with the magic number.
*
* Clients should consider alerting their users that, unlike plain data, if
* even one bit becomes corrupted, the data will be entirely unrecoverable.
* Ditto if they forget their password, there is no way to recover the data.
*
*******************************************************************************/
class tox {
/**
* The size of the salt part of a pass-key.
*/
const PASS_SALT_LENGTH = 32;
/**
* The size of the key part of a pass-key.
*/
const PASS_KEY_LENGTH = 32;
/**
* The amount of additional data required to store any encrypted byte array.
* Encrypting an array of N bytes requires N + $PASS_ENCRYPTION_EXTRA_LENGTH
* bytes in the encrypted byte array.
*/
const PASS_ENCRYPTION_EXTRA_LENGTH = 80;
error for key_derivation {
NULL,
/**
* The crypto lib was unable to derive a key from the given passphrase,
* which is usually a lack of memory issue.
*/
FAILED,
}
error for encryption {
NULL,
/**
* The crypto lib was unable to derive a key from the given passphrase,
* which is usually a lack of memory issue. The functions accepting keys
* do not produce this error.
*/
KEY_DERIVATION_FAILED,
/**
* The encryption itself failed.
*/
FAILED,
}
error for decryption {
NULL,
/**
* The input data was shorter than $PASS_ENCRYPTION_EXTRA_LENGTH bytes
*/
INVALID_LENGTH,
/**
* The input data is missing the magic number (i.e. wasn't created by this
* module, or is corrupted).
*/
BAD_FORMAT,
/**
* The crypto lib was unable to derive a key from the given passphrase,
* which is usually a lack of memory issue. The functions accepting keys
* do not produce this error.
*/
KEY_DERIVATION_FAILED,
/**
* The encrypted byte array could not be decrypted. Either the data was
* corrupted or the password/key was incorrect.
*/
FAILED,
}
/*******************************************************************************
*
* BEGIN PART 1
*
* The simple API is presented first. If your code spends too much time using
* these functions, consider using the advanced functions instead and caching
* the generated pass-key.
*
*******************************************************************************/
/**
* Encrypts the given data with the given passphrase.
*
* The output array must be at least `plaintext_len + $PASS_ENCRYPTION_EXTRA_LENGTH`
* bytes long. This delegates to ${pass_Key.derive} and
* ${pass_Key.encrypt}.
*
* @param plaintext A byte array of length `plaintext_len`.
* @param plaintext_len The length of the plain text array. Bigger than 0.
* @param passphrase The user-provided password. Can be empty.
* @param passphrase_len The length of the password.
* @param ciphertext The cipher text array to write the encrypted data to.
*
* @return true on success.
*/
static bool pass_encrypt(const uint8_t[plaintext_len] plaintext, const uint8_t[passphrase_len] passphrase, uint8_t *ciphertext)
with error for encryption;
/**
* Decrypts the given data with the given passphrase.
*
* The output array must be at least `ciphertext_len - $PASS_ENCRYPTION_EXTRA_LENGTH`
* bytes long. This delegates to ${pass_Key.decrypt}.
*
* @param ciphertext A byte array of length `ciphertext_len`.
* @param ciphertext_len The length of the cipher text array. At least $PASS_ENCRYPTION_EXTRA_LENGTH.
* @param passphrase The user-provided password. Can be empty.
* @param passphrase_len The length of the password.
* @param plaintext The plain text array to write the decrypted data to.
*
* @return true on success.
*/
static bool pass_decrypt(const uint8_t[ciphertext_len] ciphertext, const uint8_t[passphrase_len] passphrase, uint8_t *plaintext)
with error for decryption;
/*******************************************************************************
*
* BEGIN PART 2
*
* And now part 2, which does the actual encryption, and can be used to write
* less CPU intensive client code than part one.
*
*******************************************************************************/
class pass_Key {
/**
* This type represents a pass-key.
*
* A pass-key and a password are two different concepts: a password is given
* by the user in plain text. A pass-key is the generated symmetric key used
* for encryption and decryption. It is derived from a salt and the user-
* provided password.
*
* The $this structure is hidden in the implementation. It can be created
* using $derive or $derive_with_salt and must be deallocated using $free.
*/
struct this;
/**
* Deallocate a $this. This function behaves like free(), so NULL is an
* acceptable argument value.
*/
void free();
/**
* Generates a secret symmetric key from the given passphrase.
*
* Be sure to not compromise the key! Only keep it in memory, do not write
* it to disk.
*
* Note that this function is not deterministic; to derive the same key from
* a password, you also must know the random salt that was used. A
* deterministic version of this function is $derive_with_salt.
*
* @param passphrase The user-provided password. Can be empty.
* @param passphrase_len The length of the password.
*
* @return true on success.
*/
static this derive(const uint8_t[passphrase_len] passphrase)
with error for key_derivation;
/**
* Same as above, except use the given salt for deterministic key derivation.
*
* @param passphrase The user-provided password. Can be empty.
* @param passphrase_len The length of the password.
* @param salt An array of at least $PASS_SALT_LENGTH bytes.
*
* @return true on success.
*/
static this derive_with_salt(const uint8_t[passphrase_len] passphrase, const uint8_t[PASS_SALT_LENGTH] salt)
with error for key_derivation;
/**
* Encrypt a plain text with a key produced by $derive or $derive_with_salt.
*
* The output array must be at least `plaintext_len + $PASS_ENCRYPTION_EXTRA_LENGTH`
* bytes long.
*
* @param plaintext A byte array of length `plaintext_len`.
* @param plaintext_len The length of the plain text array. Bigger than 0.
* @param ciphertext The cipher text array to write the encrypted data to.
*
* @return true on success.
*/
const bool encrypt(const uint8_t[plaintext_len] plaintext, uint8_t *ciphertext)
with error for encryption;
/**
* This is the inverse of $encrypt, also using only keys produced by
* $derive or $derive_with_salt.
*
* @param ciphertext A byte array of length `ciphertext_len`.
* @param ciphertext_len The length of the cipher text array. At least $PASS_ENCRYPTION_EXTRA_LENGTH.
* @param plaintext The plain text array to write the decrypted data to.
*
* @return true on success.
*/
const bool decrypt(const uint8_t[ciphertext_len] ciphertext, uint8_t *plaintext)
with error for decryption;
}
/**
* Retrieves the salt used to encrypt the given data.
*
* The retrieved salt can then be passed to ${pass_Key.derive_with_salt} to
* produce the same key as was previously used. Any data encrypted with this
* module can be used as input.
*
* The cipher text must be at least $PASS_ENCRYPTION_EXTRA_LENGTH bytes in length.
* The salt must be $PASS_SALT_LENGTH bytes in length.
* If the passed byte arrays are smaller than required, the behaviour is
* undefined.
*
* If the cipher text pointer or the salt is NULL, this function returns false.
*
* Success does not say anything about the validity of the data, only that
* data of the appropriate size was copied.
*
* @return true on success.
*/
static bool get_salt(const uint8_t *ciphertext, uint8_t[PASS_SALT_LENGTH] salt) {
NULL,
/**
* The input data is missing the magic number (i.e. wasn't created by this
* module, or is corrupted).
*/
BAD_FORMAT,
}
/**
* Determines whether or not the given data is encrypted by this module.
*
* It does this check by verifying that the magic number is the one put in
* place by the encryption functions.
*
* The data must be at least $PASS_ENCRYPTION_EXTRA_LENGTH bytes in length.
* If the passed byte array is smaller than required, the behaviour is
* undefined.
*
* If the data pointer is NULL, the behaviour is undefined
*
* @return true if the data is encrypted by this module.
*/
static bool is_data_encrypted(const uint8_t *data);
}
%{
#ifdef __cplusplus
}
#endif
typedef TOX_ERR_KEY_DERIVATION Tox_Err_Key_Derivation;
typedef TOX_ERR_ENCRYPTION Tox_Err_Encryption;
typedef TOX_ERR_DECRYPTION Tox_Err_Decryption;
typedef TOX_ERR_GET_SALT Tox_Err_Get_Salt;
//!TOKSTYLE+
#endif // C_TOXCORE_TOXENCRYPTSAVE_TOXENCRYPTSAVE_H
%}

View File

@ -6,11 +6,10 @@
/*
* Batch encryption functions.
*/
#ifndef C_TOXCORE_TOXENCRYPTSAVE_TOXENCRYPTSAVE_H
#define C_TOXCORE_TOXENCRYPTSAVE_TOXENCRYPTSAVE_H
//!TOKSTYLE-
#ifdef __cplusplus
extern "C" {
#endif
@ -72,7 +71,7 @@ uint32_t tox_pass_key_length(void);
uint32_t tox_pass_encryption_extra_length(void);
typedef enum TOX_ERR_KEY_DERIVATION {
typedef enum Tox_Err_Key_Derivation {
/**
* The function returned successfully.
@ -90,10 +89,10 @@ typedef enum TOX_ERR_KEY_DERIVATION {
*/
TOX_ERR_KEY_DERIVATION_FAILED,
} TOX_ERR_KEY_DERIVATION;
} Tox_Err_Key_Derivation;
typedef enum TOX_ERR_ENCRYPTION {
typedef enum Tox_Err_Encryption {
/**
* The function returned successfully.
@ -117,10 +116,10 @@ typedef enum TOX_ERR_ENCRYPTION {
*/
TOX_ERR_ENCRYPTION_FAILED,
} TOX_ERR_ENCRYPTION;
} Tox_Err_Encryption;
typedef enum TOX_ERR_DECRYPTION {
typedef enum Tox_Err_Decryption {
/**
* The function returned successfully.
@ -156,7 +155,7 @@ typedef enum TOX_ERR_DECRYPTION {
*/
TOX_ERR_DECRYPTION_FAILED,
} TOX_ERR_DECRYPTION;
} Tox_Err_Decryption;
@ -188,7 +187,7 @@ typedef enum TOX_ERR_DECRYPTION {
* @return true on success.
*/
bool tox_pass_encrypt(const uint8_t *plaintext, size_t plaintext_len, const uint8_t *passphrase, size_t passphrase_len,
uint8_t *ciphertext, TOX_ERR_ENCRYPTION *error);
uint8_t *ciphertext, Tox_Err_Encryption *error);
/**
* Decrypts the given data with the given passphrase.
@ -205,7 +204,7 @@ bool tox_pass_encrypt(const uint8_t *plaintext, size_t plaintext_len, const uint
* @return true on success.
*/
bool tox_pass_decrypt(const uint8_t *ciphertext, size_t ciphertext_len, const uint8_t *passphrase,
size_t passphrase_len, uint8_t *plaintext, TOX_ERR_DECRYPTION *error);
size_t passphrase_len, uint8_t *plaintext, Tox_Err_Decryption *error);
/*******************************************************************************
@ -239,7 +238,7 @@ typedef struct Tox_Pass_Key Tox_Pass_Key;
* Deallocate a Tox_Pass_Key. This function behaves like free(), so NULL is an
* acceptable argument value.
*/
void tox_pass_key_free(struct Tox_Pass_Key *_key);
void tox_pass_key_free(struct Tox_Pass_Key *key);
/**
* Generates a secret symmetric key from the given passphrase.
@ -249,7 +248,7 @@ void tox_pass_key_free(struct Tox_Pass_Key *_key);
*
* Note that this function is not deterministic; to derive the same key from
* a password, you also must know the random salt that was used. A
* deterministic version of this function is tox_pass_key_derive_with_salt.
* deterministic version of this function is `tox_pass_key_derive_with_salt`.
*
* @param passphrase The user-provided password. Can be empty.
* @param passphrase_len The length of the password.
@ -257,7 +256,7 @@ void tox_pass_key_free(struct Tox_Pass_Key *_key);
* @return true on success.
*/
struct Tox_Pass_Key *tox_pass_key_derive(const uint8_t *passphrase, size_t passphrase_len,
TOX_ERR_KEY_DERIVATION *error);
Tox_Err_Key_Derivation *error);
/**
* Same as above, except use the given salt for deterministic key derivation.
@ -269,7 +268,7 @@ struct Tox_Pass_Key *tox_pass_key_derive(const uint8_t *passphrase, size_t passp
* @return true on success.
*/
struct Tox_Pass_Key *tox_pass_key_derive_with_salt(const uint8_t *passphrase, size_t passphrase_len,
const uint8_t *salt, TOX_ERR_KEY_DERIVATION *error);
const uint8_t *salt, Tox_Err_Key_Derivation *error);
/**
* Encrypt a plain text with a key produced by tox_pass_key_derive or tox_pass_key_derive_with_salt.
@ -283,8 +282,8 @@ struct Tox_Pass_Key *tox_pass_key_derive_with_salt(const uint8_t *passphrase, si
*
* @return true on success.
*/
bool tox_pass_key_encrypt(const struct Tox_Pass_Key *_key, const uint8_t *plaintext, size_t plaintext_len,
uint8_t *ciphertext, TOX_ERR_ENCRYPTION *error);
bool tox_pass_key_encrypt(const struct Tox_Pass_Key *key, const uint8_t *plaintext, size_t plaintext_len,
uint8_t *ciphertext, Tox_Err_Encryption *error);
/**
* This is the inverse of tox_pass_key_encrypt, also using only keys produced by
@ -296,10 +295,10 @@ bool tox_pass_key_encrypt(const struct Tox_Pass_Key *_key, const uint8_t *plaint
*
* @return true on success.
*/
bool tox_pass_key_decrypt(const struct Tox_Pass_Key *_key, const uint8_t *ciphertext, size_t ciphertext_len,
uint8_t *plaintext, TOX_ERR_DECRYPTION *error);
bool tox_pass_key_decrypt(const struct Tox_Pass_Key *key, const uint8_t *ciphertext, size_t ciphertext_len,
uint8_t *plaintext, Tox_Err_Decryption *error);
typedef enum TOX_ERR_GET_SALT {
typedef enum Tox_Err_Get_Salt {
/**
* The function returned successfully.
@ -317,7 +316,7 @@ typedef enum TOX_ERR_GET_SALT {
*/
TOX_ERR_GET_SALT_BAD_FORMAT,
} TOX_ERR_GET_SALT;
} Tox_Err_Get_Salt;
/**
@ -339,7 +338,7 @@ typedef enum TOX_ERR_GET_SALT {
*
* @return true on success.
*/
bool tox_get_salt(const uint8_t *ciphertext, uint8_t *salt, TOX_ERR_GET_SALT *error);
bool tox_get_salt(const uint8_t *ciphertext, uint8_t *salt, Tox_Err_Get_Salt *error);
/**
* Determines whether or not the given data is encrypted by this module.
@ -362,10 +361,12 @@ bool tox_is_data_encrypted(const uint8_t *data);
}
#endif
typedef TOX_ERR_KEY_DERIVATION Tox_Err_Key_Derivation;
typedef TOX_ERR_ENCRYPTION Tox_Err_Encryption;
typedef TOX_ERR_DECRYPTION Tox_Err_Decryption;
typedef TOX_ERR_GET_SALT Tox_Err_Get_Salt;
//!TOKSTYLE-
typedef Tox_Err_Key_Derivation TOX_ERR_KEY_DERIVATION;
typedef Tox_Err_Encryption TOX_ERR_ENCRYPTION;
typedef Tox_Err_Decryption TOX_ERR_DECRYPTION;
typedef Tox_Err_Get_Salt TOX_ERR_GET_SALT;
//!TOKSTYLE+